Click here to Skip to main content
15,921,697 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello,

I'm trying to find a way to convert a dataset object to xml and assign that
to a string variable without saving to a file. Obviously I don't want to
slow down the process by writing to disk, but all the methods I've found so
far (dataset.writexml) write to a file. I think there's a way to use a
stream object, but I haven't come up with anything. How can I get this done
without writing to disk?

Thanks.
Posted

How about using StringWriter[^]?

http://geekswithblogs.net/mnf/archive/2008/08/14/convert--dataset--and-datatable-to-xml-string-helper.aspx[^]

C#
public static string ToStringAsXml(DataSet ds)
{
    StringWriter sw = new StringWriter();
    ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
    string s = sw.ToString();
    return s;
}


Oops, just noticed the VB.Net tag

VB
Public Shared Function ToStringAsXml(ds As DataSet) As String
    Dim sw As New StringWriter()
    ds.WriteXml(sw, XmlWriteMode.IgnoreSchema)
    Dim s As String = sw.ToString()
    Return s
End Function
 
Share this answer
 
v3
Comments
lllyxer 3-May-11 15:42pm    
Thank you Dylan
Use a MemoryStream object.

In C#:

C#
MemoryStream stream = new MemoryStream(); 
XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); 
writer.WriteStartDocument(); 
myDataSet.WriteXML(stream); 


In VB:

VB
Dim stream As New MemoryStream()
Dim writer As New XmlTextWriter(stream, Encoding.UTF8)
writer.WriteStartDocument()
myDataSet.WriteXML(stream)
 
Share this answer
 
Comments
Simon_Whale 20-Apr-11 17:54pm    
Good call :) I;m using that technique myself it works like a charm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900