XML Parsing in .Net

Posted on October 7, 2007 
Filed Under .Net Code, CSharp, XML

While working on wxDesktop, which was my first attempt at parsing data from an XML source, I tried to find the best way to read and parse out certain data from an XML document. Before I even really got to the meat of it, I had just had it in my head that I was going to use a DataSet. Why would I do that, you ask? Well, when that’s all you know how to do, that’s usually what you go with. I have never dealt with the XML namespace, mostly because I haven’t had to. Now that I have, I know I will never use the crappy DataSet class for this ever again.

Take the following XML document.

<p>      Sample set name<br />
      5<br />
      4<br />
      6<br />
      1<br />
      20<br />
      54<br />
      10<br />
      19<br />
      17<br />
<p>      Second Sample set name<br />
      10<br />
      12<br />
      14<br />
      2<br />
      4<br />
      6<br />
      8<br />
      16<br />
      18<br />

When you read this document in using the DataSet.ReadXML function like this:
private void readXMLDataSet(string FileName)<br />
{<br />
    DataSet ds = new DataSet();<br />
    ds.ReadXml(&quot;test.xml&quot;);<br />
}<br />

The DataSet will contain 3 tables. It will contain the tables called data, value, and otherdata. Not really what you would think would be in there… It sort of makes sense, except for the fact that all value columns are then lumped into one table and then linked via an ID. While this isn’t too bad, and it would probably be usable, it’s not ideal, nor fun to use.

Now take this piece of code:

private void readXMLNodes(string FileName)<br />
{<br />
    System.Xml.XmlDocument xd = new System.Xml.XmlDocument();<br />
<p>    System.Xml.XmlNode node = xd.SelectSingleNode(&quot;/test/data&quot;);<br />
    System.Xml.XmlNode nameNode = node.SelectSingleNode(&quot;name&quot;);<br />
    System.Xml.XmlNodeList valueList = node.SelectNodes(&quot;value&quot;);<br />
}<br />

This uses the XmlDocument, XmlNode, and XmlNodeList classes and allows you to easily parse out certain parts of the XML document to find exactly what you need. nameNode.InnerText will show “Sample set name” and the valueList will contain every value in the data section. So valueList[0].InnerText will be 5.

Now, you could shove this information into a correctly laid out DataSet, but why bother? Now I see the value in creating a class just to parse certain XML documents. You can set the class up so that it will match the structure as it should be logically laid out and use the class to just access the nodes as needed through functions.


Leave a Reply