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