TLCONE
TLCONE

Reputation: 104

UWP - XDocument Equivalent Of XMLNodeList

If I had an XMLDocument and wanted to for example count the number of results of a Node I would use something like

        //XmlNodeList CountResultsReturned = XMLSearch.SelectNodes("root/item");
        //if (CountResultsReturned.Count > 1)
        //{}

I was wondering how I would achive something like this using XDocument instead.

Upvotes: 1

Views: 722

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236248

There is no specific class in LINQ to XML which is equivalent to XmlNodeList, because LINQ to XML simply works with sequence of nodes IEnumerable<XNode> or sequence of elements IEnumerable<XElement>. When you select some nodes it just yields matching nodes one by one. You can store sequence to list or other collection, if you want to. E.g

var items = xdoc.Root.Elements("item").ToList();

For your code just select elements and use LINQ Any() method to check if any elements exist:

xdoc.Root.Elements("item").Any()
// items.Any()

You can also use Count() to get number of elements. Of course XPath also available

xdoc.XPathSelectElements("root/item").Count()
// items.Count

Upvotes: 4

Related Questions