JavaSa
JavaSa

Reputation: 6241

XmlElement HasChildNodes property definition

Lets say you have this XML structure:

<Class>
       <Worker>
              <Name> Dan </Name>
              <Phone> 123 </Phone> 
                <Class>
                     <Address>
                        <Street> yellow brick road </Street>
                        <Zip Code> 123456 </Zip Code>
                     </Address>
                </Class>
         </Worker>
 </Class>   

Using XMLElement, my problem is that theHasChildNodes property of the <Name> element returns true, while I would expect it to return false.

HasChildNodes by my definition should be like this: <Worker> has children, <Address> also, but <Street> and <Name> don't have children, they have a value instead.

How can I differentiate these cases? Is there another property with the behaviour I expect?

Upvotes: 1

Views: 1809

Answers (3)

Jemin
Jemin

Reputation: 554

Here is a code in vb.net to check if a node actually has xml child elements

Function hasXmlChildElements(ByVal node As XmlNode) As Boolean
            If node.HasChildNodes AndAlso node.ChildNodes.Count = 1 AndAlso node.FirstChild.GetType.Name.ToUpper = "XMLTEXT" Then
                Return False
            End If
            Return node.HasChildNodes
    End Function

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122364

In DOM terms character content is represented as text nodes, so only completely empty element nodes (<foo/> or <bar></bar>) would have no children. You'll have to check all the child nodes to see whether any of them are XMLElement.

Upvotes: 1

Mark Pattison
Mark Pattison

Reputation: 3029

It's because the "Dan" value inside the Name element is treated as a child node.

Perhaps you could test whether the XMLElement only has an XMLText child, or whether it has no XMLElement children?

Upvotes: 2

Related Questions