2011-04-29 45 views
2

我只想檢查XML文件中是否存在某個元素。元素是深層次的。下面的代碼工作正常,但是我能想出最短的語法。任何人都可以想出一種更流利的方式,而不訴諸經典的XPath語法嗎?Linq to XML - 搜索深度元素的存在

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

回答

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

@mellamokb你是正確的;當我輸入時,我肯定一直在想java的println。 – 2011-04-29 18:39:59

+0

是的,這是行不通的,因爲我可能在任何地方都有書。我需要特定的層次結構。 – 2011-04-29 18:41:12

5

這樣的工作 - 假設你實際上需要確切的層次,因爲它們可能會在一個不相關的子樹Book節點,否則,你可以使用Descendants()

Console.WriteLine(doc.Elements("Bookstore") 
         .Elements("Books") 
         .Elements("Book") 
         .Any()); 

複數Elements()不要求null檢查,因爲如果不存在這樣的元素,它將只返回一個空的枚舉,因此它仍然是可鏈接的。

+0

好主意。我喜歡這個。謝謝。 – 2011-04-29 18:41:43

3

大概不會短,但:

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