Share via


How to: Find an Attribute of the Parent (XPath-LINQ to XML)

This topic shows how to navigate to the parent element and find an attribute of it.

The XPath expression is:

../@id

Example

This example first finds an Author element. It then finds the id attribute of the parent element.

This example uses the following XML document: Sample XML File: Books (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)

This example produces the following output:

Results are identical
id="bk101"

See Also

Concepts

LINQ to XML for XPath Users