In my last few posts on LINQ to XML (part 1, part 2 and part 3) I’ve shown you a starter on navigating around XML data. In this post I’ll continue to show you how to navigate through XML data by showing you how to navigate around sibling elements.
First consider this code:
XElement root = new XElement("root", new XElement("FirstChild"), new XElement("SecondChild"), new XElement("ThirdChild"), new XElement("FouthChild"), new XElement("FifthChild"));
Which produces the following XML structure:
We can access the ThirdChild with this code:
XElement child = root.Element("ThirdChild");
From that point, we can also get access to its siblings.
To access the siblings that occur before the element we have a reference to then we can use ElementsBeforeSelf. As with Elements this returns an IEnumerable<XElement> object which allows us to iterate over the result, like this:
IEnumerable<XElement> elements = child.ElementsBeforeSelf(); foreach (XElement element in elements) Console.WriteLine(element);
The result is:
Conversely, we can get the siblings that come after the element we have a reference to with ElementsAfterSelf. Like this:
IEnumerable<XElement> elements = child.ElementsAfterSelf();
The result in this case will be: