Get XML String from DataSet

bryker used Ask the Experts™

Take a look at this code, which writes the XML schema *and* XML data from a DataSet object to a file:

Dim oTextWriter As System.IO.TextWriter
Dim oXMLSerializer As System.Xml.Serialization.XmlSerializer
oTextWriter = New IO.StreamWriter("C:\myds.txt")
oXMLSerializer = New Xml.Serialization.XmlSerializer(GetType(System.Data.DataSet))
Call oXMLSerializer.Serialize(oTextWriter, oDataSet)
Call oTextWriter.Close()

This just works great.  I say "great" because it writes both the SCHEMA and the DATA to that target file.

What I need, though, is a way to write all that data to a String variable, in memory.  I know about DataSet.ReadXmlSchema() and DataSet.ReadXml(), but they do not do what the above does--they return only one or the other at a time.  I want the in-memory equivalent of what happens above--schema and data together, happy and free--only in memory, not to a file.

(Naturally, I don't want something as inelegant as writing all this to a file, then reading it back into a variable and then destroying the temp file.  There's a better way.)

I believe that this can be done by somehow employing a System.IO.MemoryStream, and perhaps supplying that to the StreamWriter constructor above (instead of a filepath).  I'm just too dumb/lazy to make it happen, however.

Can someone show me how?

Thanks a lot.

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®


I erred in some points in my question.  I refer to the DataSet.ReadXmlSchema() and DataSet.ReadXml() methods.  I should have instead written DataSet.GetXml() and DataSet.GetXmlSchema(), since I'm talking about reading from, not writing to, the DataSet.

Same principle applies, and so I have the same problem.  If I "feed" XML to the DataSet, I can specify how it reads it (using the XmlReadMode parameter).  But when I read *from* the DataSet (force it to write to memory), I can find no such option.  Due to these .GetXml() and .GetXmlSchema() calls, either I read schema, or I read data.

But I really need to somehow write both to memory, so that I can end up with a single String which completely describes this DataSet, structure and data.
Use StringWriter object to write the data to string.

DataSet myDS; // Assuming that you alreadyhave got DataSet

StringWriter sw = new StringWriter();

string myVal = sw.GetStringBuilder().ToString();

Now myVal variable will have XML value.


Seems to work fine.  Thanks.
how to give rights to an xml file. I have 2 XMl file in my project but file acces error occurs when i try to access contents of xml file. if i use my local lan n/w it works properly . is there any rights r required to aspnet user or what ?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial