What is the LINQ to XML equivalent for this XPath

I am wondering what the “best way” (in C #) is to implement this xpath request using LINQ:

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

I need an IEnumerable "nodesIWantReturned" list, but only from a specific section of the XML tree depending on the value of the ancestor attributes.

+4
source share
3 answers

More verbal solution:

 var nodesIWantReturned = from m in doc.Elements("topNode").Elements("middleNode") from p in m.Elements("penultimateNode") from n in p.Elements("nodesIWantReturned") where m.Attribute("filteringAttribute").Value == "filterValue" where p.Attribute("anotherFilterAttribute").Value == "somethingElse" select n; 
0
source

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

The class notes that these methods are slower than the “correct” Linq-to-XML, but it’s not very important a lot of time, and sometimes it’s easier to just use XPath (it is certainly a lot of terser!).

 var result = doc.XPathSelectElements("your xpath here"); 
+10
source
 var result = root.Elements("topNode") .Elements("middleNode") .Where(a => (string)a.Attribute("filteringAttribute") == "filterValue") .Elements("penultimateNode") .Where(a => (string)a.Attribute("anotherFilterAttribute") == "somethingElse") .Elements("nodesIWantReturned"); 
+3
source

All Articles