39

I'm tring to get a string from a DataSet without using GetXml. I'm using WriteXml, instead. How to use it to get a string? Thanks

pistacchio
  • 53,670
  • 101
  • 270
  • 404

3 Answers3

69
StringWriter sw = new StringWriter();
dataSet.WriteXml(sw);
string result = sw.ToString();
mmx
  • 402,675
  • 87
  • 836
  • 780
  • 3
    Out of interest, this fails on really large datasets (like it does on GetXML()) System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity) – Rodney May 31 '11 at 01:21
  • 1
    VB.Net Version: `Dim sw As IO.StringWriter = New IO.StringWriter()` `dataset_name.WriteXml(sw)` `Dim result As String = sw.ToString()` – Jeff Dec 05 '13 at 22:20
8

Write to a StringWriter, and then call ToString on that.

Note that if you want the generated XML declaration to specify UTF-8 instead of UTF-16, you'll need something like my Utf8StringWriter.

Community
  • 1
  • 1
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
1

here is the vb.net code:

 Private Function GenerateXML(ByVal ds As DataSet) As String
    Dim obj As New StringWriter()
    Dim xmlstring As String
    ds.WriteXml(obj)
    xmlstring  = obj.ToString()
    Return xmlstring 
End Function
DareDevil
  • 5,159
  • 5
  • 48
  • 85