Share via


How to: Find Attributes of Siblings with a Specific Name (XPath-LINQ to XML)

This topic shows how to find all attributes of the siblings of the context node. Only attributes with a specific name are returned in the collection.

The XPath expression is:

../Book/@id

Example

This example first finds a Book element, and then finds all sibling elements named Book, and then finds all attributes named id. The result is a collection of attributes.

This example uses the following XML document: Sample XML File: Books (LINQ to XML).

XDocument books = XDocument.Load("Books.xml");

XElement book = 
    books
    .Root
    .Element("Book");

// LINQ to XML query
IEnumerable<XAttribute> list1 =
    from el in book.Parent.Elements("Book")
    select el.Attribute("id");

// XPath expression
IEnumerable<XAttribute> list2 =
  ((IEnumerable)book.XPathEvaluate("../Book/@id")).Cast<XAttribute>();

if (list1.Count() == list2.Count() &&
        list1.Intersect(list2).Count() == list1.Count())
    Console.WriteLine("Results are identical");
else
    Console.WriteLine("Results differ");
foreach (XAttribute el in list1)
    Console.WriteLine(el);
Dim books as XDocument = XDocument.Load("Books.xml")
Dim book As XElement = books.Root.<Book>(0)

' LINQ to XML query
Dim list1 As IEnumerable(Of XAttribute) = _
    From el In book.Parent.<Book> _
    Select el.Attribute("id")

' XPath expression
Dim list2 As IEnumerable(Of XAttribute) = DirectCast(book. _
    XPathEvaluate("../Book/@id"), IEnumerable).Cast(Of XAttribute)()

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 XAttribute In list1
    Console.WriteLine(el)
Next

This example produces the following output:

Results are identical
id="bk101"
id="bk102"

See Also

Concepts

LINQ to XML for XPath Users