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
);
Console.WriteLine(doc.Root.Descendants("Book").Any());
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.
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