Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to XML select multiple elements?

Tags:

linq-to-xml

How do I select multiple elements (with different names) in a LINQ to XML query?

I have a query like this:

var elems = from descendant in doc.Descendants("foo")
                            select descendant;

But I want to select both foo and bar, sort of like this:

var elems = from descendant in doc.Descendants("foo" || "bar")
                            select descendant;

But that is just to illustrate what I want to do, I know this is not correct syntax. I don't know how it should be done with LINQ to XML, so what is the proper way to do it?

like image 851
Anders Avatar asked Apr 15 '26 10:04

Anders


1 Answers

You can only pass in one XName into those methods. Just leave them out there and do normal LINQ filtering.

var elems = doc.Descendants()
               .Where(desc => desc.Name == "foo" || desc.Name == "bar");

Using an XPath is another way.

var elems = doc.XPathSelectElements("//foo|//bar");
like image 114
Jeff Mercado Avatar answered Apr 18 '26 17:04

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!