Handleman
Handleman

Reputation: 754

What is the LINQ to XML equivalent for this 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.

Upvotes: 4

Views: 3860

Answers (3)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422270

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");

Upvotes: 3

Greg Beech
Greg Beech

Reputation: 136727

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");

Upvotes: 10

bruno conde
bruno conde

Reputation: 48255

A 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;

Upvotes: 0

Related Questions