Jer*_*ter 2 c# xml 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
        );
这可行 - 假设您确实需要确切的层次结构,因为它们可能是Book不相关的子树中的节点,否则您可以使用Descendants():
Console.WriteLine( doc.Elements("Bookstore")
                      .Elements("Books")
                      .Elements("Book")
                      .Any());
复数Elements()不需要null检查,因为如果不存在这样的元素,它将只返回空枚举,因此它仍然是可链接的.
| 归档时间: | 
 | 
| 查看次数: | 1275 次 | 
| 最近记录: |