次の方法で共有


方法 : 親の属性を検索する (XPath-LINQ to XML)

このトピックでは、親要素に移動してその属性を検索する方法を示します。

XPath 式を次に示します。

../@id

使用例

この例では、まず Author 要素を検索します。 次に、親要素の id 属性を検索します。

この例では、「サンプル XML ファイル : 書籍 (LINQ to XML)」の 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"

参照

概念

XPath ユーザー向けの LINQ to XML