LINQ to XML -How to use XPass for elements selection

I am just starting to work with LINQ to XML and tried to find child document similar to the following:
 xml.Element(“client/child”);
But it throw exception
System.Xml.XmlException: The ‘/’ character, hexadecimal value 0x2F, cannot be included in a name.
The reason is that LINQ to XML doesn’t directly support XPAth
Fortunately there are extensions, that allow to use XPath for XElement search/selection.

using System.Xml.XPath;

and then

var clients = xml.XPathSelectElements ( “client/child” );

Consider, if required ,an XPathSelectElements overload  with namespace management.

Note, that XPath extensions are actually backward compatibility feature, and Microsoft recommends to use native XElement methods, such as Descendants ,Elements,Element etc.  See Comparison of XPath and LINQ to XML
 However K. Scott Allen  prefers to mix LINQ and XPath  to have concise code.

See also Concepts LINQ to XML for XPath Users

Useful tip:where clause and “Possible System.NullReferenceException”

Advertisements