Working with XML Strings

Published 16 October 03 10:29 AM | Scott Mitchell

Pop-quiz, hotshot: you have received a payload of XML data in the form of a string from, say, a Web service. Now, you want to perhaps parse this XML data, and perhaps display it in a DataGrid. What do you do, hotshot, what do you do?

Ideally, it would be nice to be able to load the data into one of the many XML-related classes the .NET Framework BCL provides, perhaps the XmlDocument. XmlDocument contains a Load() method, so you think to yourself, "Ok, here's what I'll do:"

// Create a new XmlDocument instance...
XmlDocument xmlDoc = new XmlDocument();

// Load the XML string data...
xmlDoc.Load("Mitchell");

That won't work, though. The XmlDocument's Load() will accept a string input parameter, but it expects it to be either a URL or a file path where the XML data can be found. Drag. The Load() method, however, can also accept a TextReader instance. Therefore, we can load the XML string data into a StringReader instance, (which is derived from the TextReader class), and then pass in this StringReader into the Load() method!

// Create and populate a StringReader StringReader
sr = new StringReader("Mitchell");

// Create a new XmlDocument instance...
XmlDocument xmlDoc = new XmlDocument();

// Load the XML string data...
xmlDoc.Load(sr);

I recently wrote up a FAQ discussing this in more detail. Also worth checking out is this article by Anthony Hart: DataGrids, DataSets, and XML Strings.

Happy Programming!

Update
A bit of searching the docs has revealed that the XmlDocument class contains a LoadXml() method that loads from XML string data. So... I guess you could use that (assuming you don't need to validate the XML upon loading - for that you still need to use the Load() method). :-) However, for things like XmlTextReaders and whatnot, you will still need to use StringReaders for loading XML string data....

Filed under:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.