doosh
doosh

Reputation: 875

Iterate through each XElement in an XDocument

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".

Upvotes: 13

Views: 39419

Answers (2)

CodeGuru
CodeGuru

Reputation: 2803

Do like this :

string xml = "  <span><myVal>One</myVal><myVal>Two</myVal><myVal>Three</myVal><myVal>Four</myVal><myVal>Five</myVal></span>";
XmlReader xr = XmlReader.Create(new StringReader(xml));
var xMembers = from members in XElement.Load(xr).Elements() select members;

foreach (XElement x in xMembers)
{
    var nodeValue = x.Value;
}

Now if you see the value of nodeValue you will get One Two etc

Upvotes: 2

Bennor McCarthy
Bennor McCarthy

Reputation: 11675

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/>).

Upvotes: 18

Related Questions