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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With