Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the LINQ to XML equivalent for this XPath

Tags:

c#

xml

linq

xpath

I wondering what the "best practice" way (in C#) is to implement this xpath query with LINQ:

/topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned

I would like an IEnumerable list of the 'nodesIWantReturned', but only from a certain section of the XML tree, dependent on the value of ancestor attributes.

like image 998
Handleman Avatar asked Dec 13 '22 05:12

Handleman


1 Answers

In addition to the Linq methods shown, you can also import the System.Xml.XPath namespace and then use the XPathSelectElements extension method to use your XPath query directly.

It is noted in the class that these methods are slower than 'proper' Linq-to-XML, however a lot of the time this isn't too important, and sometimes it's easier just to use XPath (it's certainly a lot terser!).

var result = doc.XPathSelectElements("your xpath here");
like image 139
Greg Beech Avatar answered Jan 01 '23 11:01

Greg Beech