Over a million developers have joined DZone.

From DataSet To XmlDocument

·
Ever had to take a DataSet from the database and turn it into an Xml Document in .NET? The process is a little messy because there is no direct conversion method. This is because Xml is streamed from the DataSet but the XmlDocument needs a string to load from. Here's my solution:


 // This is the final document
XmlDocument Data = new XmlDocument();

// Create a string writer that will write the Xml to a string
StringWriter stringWriter = new StringWriter();

// The Xml Text writer acts as a bridge between the xml stream and the text stream
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

// Now take the Dataset and extract the Xml from it, it will write to the string writer
content.WriteXml(xmlTextWriter, XmlWriteMode.IgnoreSchema);

// Write the Xml out to a string
string contentAsXmlString = stringWriter.ToString();

// load the string of Xml into the document
Data.LoadXml(contentAsXmlString);
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}