anon
anon

Reputation:

Check whether an XML Element has child elements or a value

Im using .NET's XMLDocument as a container for an XML file and when I use:

document.GetElementsByTagName("ElementX")[0].HasChildNodes

It returns true for all elements even when the element looks like so:

<ElementX>
    <A>1</A>
    <B>2</B>
    Some value
</ElementX>

Or

<ElementX>Some Value</ElementX>

Example one clearly has child elements but the second example does not yet both seem to return true. Im guessing that XMLDocument counts any value (Even if its not an element) as a child? Is there a way I can check if an element contains just text or an element(s). Thanks in advance.

Upvotes: 4

Views: 11813

Answers (1)

Mike
Mike

Reputation: 240

Your current code:

document.GetElementsByTagName("ElementX")[0].HasChildNodes

is returning that root node ElementX. GetElementsByTagName returns an XmlNodeList of elements matching that tagname. So you're just getting the root, which has child nodes.

But that won't solve your problem, if I have your question right, because those text values 1 and 2 are nodes according to this library! Gasp! They're XmlText objects though, not elements.

Are you looking for any node that has an XmlElement underneath it? If so, you are probably looking for this:

child.ChildNodes.OfType<XmlElement>().Any()

Run this humdinger to see what I mean:

internal static class Program
{
    private static void Main()
    {
        var doc = new XmlDocument();
        doc.LoadXml("<ElementX><A>1</A><B>2</B>Some value</ElementX>");
        Console.WriteLine("{0,15}{1,15}{2,15}{3,15}","Name","Children","ChildElements","Value");
        foreach (XmlElement e in doc.GetElementsByTagName("ElementX"))
            ChildNodeCheck(e);
    }

    private static void ChildNodeCheck(XmlNode element)
    {
        Console.WriteLine("{0,15}{1,15}{2,15}{3,15}", 
            element.Name, 
            element.HasChildNodes, 
            element.ChildNodes.OfType<XmlElement>().Any(), 
            element.Value);

        if (!element.HasChildNodes) return;
        foreach(XmlNode child in element.ChildNodes)
            ChildNodeCheck(child);
    }
}

Upvotes: 8

Related Questions