I am parsing an XML document using LINQ to XML and XDocument
. Is there a way for a XElement
/XContainer
to get a child node by the index (in document order)? So that I can get the n
th node of the element?
I know I can probably do that by getting all the child nodes of that element and converting that IEnumerable
to a List
, but that already sounds like it would add a highly redundant overhead (as I am only interested in a single child node).
Is there something I missed in the documentation?
No, there is no indexed access to a child element using XElement
or XContainer
. If you want indexed access, you have two options.
The first is to call the Elements
method on XContainer
(which returns an IEnumerable<T>
of XElement
instances in document order) and then use the Skip
extension method to skip over the elements to reach the particular child.
If you want to access the child elements often by index, then you should place them in a IList<T>
(which has indexed access), which is easy enough with the ToList
extension method:
IList<XElement> indexedElements = element.Elements().ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With