LINQ to XML selects multiple elements?

How to 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:

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

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

+3
source share
2 answers

You can only pass one XNameto these methods. Just leave them there and do normal LINQ filtering.

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

Using XPath is another way.

var elems = doc.XPathSelectElements("//foo|//bar");
+7
source

Well, one of the options:

var elems = doc.Descendants().Where(x => x.Name == (XName) "foo" ||
                                         x.Name == (XName) "bar");
+4
source

Source: https://habr.com/ru/post/1787918/


All Articles