Iterate through each XElement in an XDocument

c#, linq-to-xml

Solution

Use `doc.Root.Elements()` (for direct children of the root node, which I think is really what you want) or `doc.Root.Descendants()` (if you want every descendant, including any possible child of `<myVal/>`).

Problem

I have an XML that looks like this: ``` <myVal>One</myVal> <myVal>Two</myVal> <myVal>Three</myVal> <myVal>Four</myVal> <myVal>Five</myVal> ``` I want to load that into an XDocument and then iterate through each XElement in that XDocument and count the number of characters in each element. What is the best way of doing that? First off, I noticed I have to add a root element or XDocument.Parse() would not be able to parse it as XML. So I added: ``` <span> <myVal>One</myVal> <myVal>Two</myVal> <myVal>Three</myVal> <myVal>Four</myVal> <myVal>Five</myVal> </span> ``` But then when I do: ``` foreach (XElement el in xDoc.Descendants()) ``` `el` will contain the entire XML, starting with the first `<span>`, including each and every one of the `<myVal>`s and then ending with `</span>`. How do I iterate through each of the XML elements (`<myVal>One</myVal>` etc) using XDocument? I don't know on beforehand what all the XML elements will be named, so they will not always be named "myVal".

Original source