HOW TO:尋找同層級節點 (XPath-LINQ to XML)
更新: November 2007
您可能想要尋找具有特定名稱之節點的所有同層級。如果內容節點也有特定的名稱,所產生的集合可能包含內容節點。
XPath 運算式為:
../Book
範例
此範例會先尋找 Book 項目,然後尋找名稱為 Book 的所有同層級項目。所產生的集合包含內容節點。
此範例使用下列 XML 文件:XML 範例檔:書籍 (LINQ to XML).
XDocument books = XDocument.Load("Books.xml");
XElement book =
books
.Root
.Elements("Book")
.Skip(1)
.First();
// LINQ to XML query
IEnumerable<XElement> list1 =
book
.Parent
.Elements("Book");
// XPath expression
IEnumerable<XElement> list2 = book.XPathSelectElements("../Book");
if (list1.Count() == list2.Count() &&
list1.Intersect(list2).Count() == list1.Count())
Console.WriteLine("Results are identical");
else
Console.WriteLine("Results differ");
foreach (XElement el in list1)
Console.WriteLine(el);
Dim books As XDocument = XDocument.Load("Books.xml")
Dim book As XElement = books.Root.<Book>.Skip(1).First()
' LINQ to XML query
Dim list1 As IEnumerable(Of XElement) = book.Parent.<Book>
' XPath expression
Dim list2 As IEnumerable(Of XElement) = book.XPathSelectElements("../Book")
If list1.Count() = list2.Count() And _
list1.Intersect(list2).Count() = list1.Count() Then
Console.WriteLine("Results are identical")
Else
Console.WriteLine("Results differ")
End If
For Each el As XElement In list1
Console.WriteLine(el)
Next
此範例會產生下列輸出:
Results are identical
<Book id="bk101">
<Author>Garghentini, Davide</Author>
<Title>XML Developer's Guide</Title>
<Genre>Computer</Genre>
<Price>44.95</Price>
<PublishDate>2000-10-01</PublishDate>
<Description>An in-depth look at creating applications
with XML.</Description>
</Book>
<Book id="bk102">
<Author>Garcia, Debra</Author>
<Title>Midnight Rain</Title>
<Genre>Fantasy</Genre>
<Price>5.95</Price>
<PublishDate>2000-12-16</PublishDate>
<Description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</Description>
</Book>