Jeremy Foster
Jeremy Foster

Reputation: 4763

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
        );

Upvotes: 2

Views: 1435

Answers (3)

Bala R
Bala R

Reputation: 108937

Console.WriteLine(doc.Root.Descendants("Book").Any());

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Probably not shorter but:

var isBookExist = 
    (from store in doc.Elements("Bookstore")
     from books in store.Elements("Books")
     from book in books.Elements("Book")
     select book).Any();

Upvotes: 3

BrokenGlass
BrokenGlass

Reputation: 160852

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.

Upvotes: 5

Related Questions