In the last post of the series, we”ve seen how easy it is to navigate along the axis with the new LINQ To XML API. At the time, I”ve promised another post on how to use XPath to navigate along the XML tree. That”s the objective of today”s post.
If you look carefully at the XElement class (or at its base, XNode), you”ll see that there really isn”t any method that expects an XPath expression. So, your first reaction might be thinking that XPath queries aren”t supported by this API. On the other hand, and since I”m writing a post on how to use XPath, you”re probably expecting a trick to query a XML tree with these kind of expressions
I”m sorry to disappoint you, but this time the only thing you need to know is that the methods responsible for letting you apply XPath expressions are implemented as extension methods on the System.Xml.XPath.Extensions class. This means that after introducing the namespace with a using expression, you should be able to see those methods as instance methods (that is, if you”re using VS and have intellisense on – btw, does anyone else have it off? ).
So,if we go back to the example presented here,that means that we should be able to get all the clients with the following XPath expression:
var clients = xml.XPathSelectElements( “//client” );
This method will return a collection of XElements (IEnumerable<XElement>) when there are nodes that match the XPath expression that was passed to the method. There”s also a XPathSelectElement method which, as you might expect, returns a single XElement (the first one, if there”s more than one). Btw, you should also note that there are a couple of other utility methods on the Extensions class.
For instance, the CreateNavigator method will give you a XPathNavigator instance that you can use to navigate the XML tree. Finally, there”s also a XPathEvaluate method which will also let you evaluate a XPath expression (with LINQ, you”ll normally use the XPathSelectElements since it returns a IEnumerable<XElement>).
And that”s all for today. Btw, I”ve just noticed that I”m still missing a post on how to change an existing XML document. That”s what we”ll talk about tomorrow. Stay tunned!