Tuesday 10 March 2009

Reading XML with XPath

There's more than one way to read an XML file in dot net, but the XPath model doesn't seem to be terribly widely documented. Which is a shame because although it's a little unintuitive, it offers some functionality that doesn't come with other tools.


using System.Xml.XPath;

XPathDocument xDoc = new XPathDocument(“filepath”);
XPathNavigator xNav = xDoc.CreateNavigator();

Xnav.MoveToRoot();
Xnav.MoveToFirstChild();

do
{
//do stuff .. like xNav.GetAttribute(""AttributeName", "");
}
while (Xnav.MoveToNext());


So, load your xml file by replacing "filepath" with the path of the - ahem - file you want to load. MoveToRoot and MoveToFirstChild do exactly what you'd expect them to, and you can obviously vary these commands depending on where you want to start reading. Then the do-while loop should pass through each node in turn, allowing you to access its attributes and such.

No comments:

Post a Comment