Consuming XML Through XmlDocument or XmlTextReader

Had to write this down else I know I’m going to forget AGAIN. Its really basic stuff but here are the methods to consuming XML using a string using the classes in the System.Xml namespace in .NET Framework.

The first method to load an XML document contained within a string is to load it into the System.Xml.XmlDocument class. To load it use the LoadXml(string xml) method. Its ridiculously simple, I know, but I totally forgot how to do it and was extremely annoyed with myself. Alternatively if its in an XML file format, you can use the Load(string filename) method to load the XML from a file. Here is an example.

The second method to load an XML document contained within a string is to load it into the System.Xml.XmlTextReader class. To do this you first create a System.IO.StringReader object and pass the string to it in the constructor. Once you have the System.IO.StringReader object you now have an object that inherits from TextReader with your string in it and you can pass it to the System.Xml.XmlTextReader in the constructor. Here is an example.
TIP: You can specify to the reader object to ignore whitespace by setting the WhitespaceHandling property on the System.Xml.XmlTextReader object to WhitespaceHandling.None.

Whats the difference between the two methods? Well for me the main difference is that System.Xml.XmlDocument allows you to perform queries using XPath syntax through the use of the SelectNodes(string xpath) and SelectSingleNode(string xpath) methods. With the System.Xml.XmlTextReader you can traverse the entire XML tree very easily. Just call the Read() method and it will read the next node then you can perform a test on the NodeType property and if it matches the XmlNodeType you are looking for, perform your queries on the attributes all you want or get the value of it or whatever.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s