我只想檢查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
);
@mellamokb你是正確的;當我輸入時,我肯定一直在想java的println。 – 2011-04-29 18:39:59
是的,這是行不通的,因爲我可能在任何地方都有書。我需要特定的層次結構。 – 2011-04-29 18:41:12