As mentioned in the previous section, XmlDocument consumes more memory and is probably slightly slower than the XmlReader approach. However, for many purposes, working with XmlDocument can be easy and often require less code. Once XML content has been read, you can read the data in a graded manner, such as XML structure, with the basic element, which can have hair elements, which can be hair elements, and so on. In the last chapter, we parse XML data from the European Central Bank, which can tell us about the current currency exchange rates, and we will do the same with the XMLDCost class.
XML can be found at current URL (http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml) and the data we need is in <Cube> elements in a tree's structure, something looks like :
<gesmes:Envelope>
[other child nodes]
<Cube>
<Cube time="2011-04-12">
<Cube currency="USD" rate="1.4470"/>
<Cube currency="JPY" rate="121.87"/>
…
Gesmes: The envelope is our basic element, which we can get using the Document Element property. We will then be able to reach the children of this node using the child nodes collection property. In our example, we want the hair nodes to leave three levels below the root / document element. We can use the following code, which basically does the same in the previous chapter as XmlReader based code:
using System;
using System.Text;
using System.Xml;
namespace ParsingXml
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
foreach(XmlNode xmlNode in xmlDoc.DocumentElement.ChildNodes[2].ChildNodes[0].ChildNodes)
Console.WriteLine(xmlNode.Attributes["currency"].Value + ": " + xmlNode.Attributes["rate"].Value);
Console.ReadKey();
}
}
}
As you can see, we use the cube nodes by going down the hair nodes hierarchy. From the DocumentElement, we ask for the third child's node (based on zero-indexed), then we ask for the baby node before that, and then we demand the entire collection of hair nodes. Obviously this is only possible because we know the structure of the XML document, and it is definitely not very flexible, beautiful or easy to change later. However, the way you navigate an XML document depends on very much XML source and the data you need. For this example, the above work is just fine and even with very limited amount of code, but for other purposes, you may want to use a bit more code to increase the readability.
Once we have a node at the rate of currency, then we use both the properties that we are connected to inside and then output them to the console, such as the example in the previous section.