41

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
  • 56,889
  • 107
  • 278
  • 420

4 Answers4

71
string result = null;

using (TextWriter sw = new StringWriter())
{
    dataSet.WriteXml(sw);
    result = sw.ToString();
}
shmnff
  • 647
  • 2
  • 15
  • 31
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 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
9

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,421,763
  • 867
  • 9,128
  • 9,194
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,249
  • 6
  • 50
  • 88
0

public string ConvertDatatableToXML(DataTable dt)

        MemoryStream str = new MemoryStream();
        dt.WriteXml(str, true);
        str.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(str);
        string xmlstring = "";
        xmlstring = sr.ReadToEnd();
        return (xmlstring);
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 26 '22 at 16:15