HOW TO:尋找父代的屬性 (XPath-LINQ to XML)
這個主題顯示如何導覽到父項目並尋找其屬性。
XPath 運算式為:
../@id
範例
這個範例會先尋找 Author 項目。 接著,它會尋找父項目的 id 屬性。
此範例使用下列 XML 文件:XML 範例檔:書籍 (LINQ to XML)。
XDocument books = XDocument.Load("Books.xml");
XElement author =
books
.Root
.Element("Book")
.Element("Author");
// LINQ to XML query
XAttribute att1 =
author
.Parent
.Attribute("id");
// XPath expression
XAttribute att2 = ((IEnumerable)author.XPathEvaluate("../@id")).Cast<XAttribute>().First();
if (att1 == att2)
Console.WriteLine("Results are identical");
else
Console.WriteLine("Results differ");
Console.WriteLine(att1);
Dim books As XDocument = XDocument.Load("Books.xml")
Dim author As XElement = books.Root.<Book>.<Author>.FirstOrDefault()
' LINQ to XML query
Dim att1 As XAttribute = author.Parent.Attribute("id")
' XPath expression
Dim att2 As XAttribute = DirectCast(author.XPathEvaluate("../@id"), _
IEnumerable).Cast(Of XAttribute)().First()
If att1 Is att2 Then
Console.WriteLine("Results are identical")
Else
Console.WriteLine("Results differ")
End If
Console.WriteLine(att1)
這個範例產生下列輸出:
Results are identical
id="bk101"