Linq to XML - 搜索深层元素是否存在
我只想检查 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
);
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
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可行 - 假设您确实需要确切的层次结构,因为它们可能是不相关子树中的 Book 节点,否则您可以使用 Descendants() :
复数 < code>Elements() 不需要
null
检查,因为如果不存在这样的元素,它只会返回一个空枚举,因此它仍然是可链接的。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 useDescendants()
:The plural
Elements()
does not require thenull
check since it will just return an empty enumeration if no such element exists, so it is still chainable.可能不会更短,但是:
Probably not shorter but: