joelc joelc - 1 month ago 7
C# Question

Iterate each node in XmlDocument by what it contains

I'm having a difficult time determining while iterating each node in an XML document (recursively) determining if the current node has a value, or, if it has embedded XML.

It seems that XmlNode.NodeType is set to Element in both cases, and in cases where the XML has a value (and not more XML) the ChildNodes.Count is not null (actually, it's 1).

A simple XML file I'm using for testing is:

<note>
<to>You</to>
<from>Me</from>
<subject>Hello!</subject>
<body>Check out this cool data!</body>
<data>
<name>Something cool</name>
<location>Mars</location>
<distance>54 million kilometers</distance>
</data>
</note>


Each of the XmlNodes above is 'Element' and with ChildNodes >= 1.

What can I use to reliably test if an XmlNode should be treated as a container (like note and data) or as holding a value (like to, from, subject, body, name, location, distance)?

Answer

I don't know if you can use System.Xml.Linq.XElement instead of XmlDocument here but if you can, you can go about this the following way:

var xml = XElement.Parse("<note> .... </note>");

then

xml.Elements().Count()

returns 5 the correct number of subnodes, whereas

xml.Elements().First().Elements().Count()

returns 0 because the to node has zero children...