Avi.S.
Avi.S.

Reputation: 163

how to check xmlnode for innertext or value in c#?

I created xmlnodelist and i want to handle the value of elements that dont have childs. at the following code i'm checking for childnodes and i get true from all of the elements, even those without childs. how can i pick the last elements in the tree and handle the value's?

XmlDocument XDoc = new XmlDocument();
            XDoc.Load("d://avi.xml");
            XmlNodeList XList = XDoc.SelectNodes("//*");
            foreach (XmlElement XNode in XList)
            {
                    if (XNode.HasChildNodes == true)
                    {
                        Console.WriteLine("this node has childs");
                        continue;
                    }
                    else Console.WriteLine("this node dont have childs");      
            } 


<level1>
    <level2>
        <level3>header3</level3>
        <level4>another</level4>
        <level31>header31</level31>
    </level2>
    <level2>
        <level3>111</level3>
        <level31>nn</level31>
    </level2>
</level1>

Upvotes: 2

Views: 965

Answers (2)

D Stanley
D Stanley

Reputation: 152594

The text within an element is a "node" as well. What you want is

if (XNode.ChildNodes.Any(n=>n.NodeType == XmlNodeType.Element))

Alternatively you can loop through the ChildNodes and see if one of them is an element.

Upvotes: 1

L.B
L.B

Reputation: 116168

How about using Linq to Xml for this?

var xElem = XElement.Parse(xml);

var leafElements = xElem.Descendants()
                        .Where(e => !e.HasElements)
                        .ToList();

Upvotes: 2

Related Questions