我只是想查看我的XML文件中是否存在某个元素。元素有几个层次。以下代码工作正常,但是我能想出的最短语法。有没有人能想到一种更流利的方法,而不需要使用经典的XPath语法?
//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
);
答案 0 :(得分:6)
Console.WriteLine(doc.Root.Descendants("Book").Any());
答案 1 :(得分:5)
这可行 - 假设您确实需要确切的层次结构,因为它们可能是不相关的子树中的Book
节点,否则您可以使用Descendants()
:
Console.WriteLine( doc.Elements("Bookstore")
.Elements("Books")
.Elements("Book")
.Any());
复数Elements()
不需要null
检查,因为如果不存在这样的元素,它将只返回空枚举,因此它仍然是可链接的。
答案 2 :(得分:3)
可能不会更短但是:
var isBookExist =
(from store in doc.Elements("Bookstore")
from books in store.Elements("Books")
from book in books.Elements("Book")
select book).Any();