Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexed access to XElement‘s child nodes

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 nth 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?

like image 514
poke Avatar asked Dec 21 '22 16:12

poke


1 Answers

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();
like image 55
casperOne Avatar answered Dec 24 '22 06:12

casperOne