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"

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted @ Wednesday, May 20, 2009 9:58 PM
Print

Comments on this entry:

No comments posted yet.

Your comment:



(not displayed)


 
 
 
 
 

Live Comment Preview:

 
«February»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910