Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to XML - Searching for Existence of a Deep Element

I simply want to check to see if a certain element exists in my XML file. The element is a few levels deep. The following code works fine, but is the shortest syntax I can come up with. Can anyone think of a way to do this more fluently without resorting to classic XPath syntax?

        //create simple sample xml
        XDocument doc = new XDocument(
        new XDeclaration("1.0", "utf-8", "yes"),
        new XElement("Bookstore",
            new XAttribute("Name", "MyBookstore"),
            new XElement("Books",
                new XElement("Book",
                    new XAttribute("Title", "MyBook"),
                    new XAttribute("ISBN", "1234")))));

        //write out a boolean indicating if the book exists
        Console.WriteLine(
            doc.Element("Bookstore") != null &&
            doc.Element("Bookstore").Element("Books") != null &&
            doc.Element("Bookstore").Element("Books").Element("Book") != null
        );
like image 937
Jeremy Foster Avatar asked Jan 26 '26 22:01

Jeremy Foster


2 Answers

Console.WriteLine(doc.Root.Descendants("Book").Any());
like image 178
Bala R Avatar answered Jan 29 '26 12:01

Bala R


This would work - assuming you actually do need the exact hierarchy because they might be a Book node in an unrelated sub tree, otherwise you can use Descendants():

Console.WriteLine( doc.Elements("Bookstore")
                      .Elements("Books")
                      .Elements("Book")
                      .Any());

The plural Elements() does not require the null check since it will just return an empty enumeration if no such element exists, so it is still chainable.

like image 29
BrokenGlass Avatar answered Jan 29 '26 10:01

BrokenGlass



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!