How to find sibling nodes (LINQ to XML)
This article shows how to use XPathSelectElements to find all siblings of a node that have a specific name, and how to use LINQ to XML query to do the same thing.
Note
The resulting collection includes the context node if it also has the specific name.
Example: Find an element named Book
, and all sibling elements named Book
This example first finds a Book
element in XML document Sample XML file: Books, and then finds all sibling elements named Book
. The resulting collection includes the context node.
The XPath expression is ../Book
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
This example produces the following output:
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>
See also
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for