Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through each XElement in an XDocument

Tags:

c#

linq-to-xml

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

like image 773
doosh Avatar asked Mar 15 '13 13:03

doosh


People also ask

What does XElement mean?

The XElement class represents an XML element with a Name property of the type XName. The XName class is composed of a local name and a namespace. Optionally, XElement can contain XML attributes of type XAttribute, derives from XContainer, and inherits the members of XContainer, XNode, and XObject.


2 Answers

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

like image 166
Bennor McCarthy Avatar answered Sep 21 '22 22:09

Bennor McCarthy


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

like image 26
CodeGuru Avatar answered Sep 21 '22 22:09

CodeGuru