joelc joelc - 4 months ago 28
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:

<body>Check out this cool data!</body>
<name>Something cool</name>
<distance>54 million kilometers</distance>

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)?


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>");



returns 5 the correct number of subnodes, whereas


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