Search code examples
c#xmlvisual-studio-2010xmlreader

How to check for CML child nodes in C#


I'm using xmlreader to read an XML-file. I want to identify whether an element has child nodes or not.

Currently, I use the IsEmptyElement method to find whether there are child elements. I found out that, even if the tag contains text data and not an element, it returns as true.

if (!file.IsEmptyElement) {
    elem.subElems.Add(readXml(file));
}

How van I fix this issue using the xml reader? Any help would be appreciated.

Thank you.


Solution

  • If you just have to check, use XmlDocument instead... I found it to be easier to understand and code.

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("YourDocument");
    
    XmlNode root = doc.FirstChild;
    
    if (root.HasChildNodes)
    {
        // Do something...
    }
    

    Reader:

    using (XmlReader reader = ...)
    {
        while (reader.Read())
        {
            if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == ...))
            {
                Int32 childrenCount = CountChildred(reader, XmlNodeType.Element);
                // Your code...
    
    public static Int32 CountChildred(XmlReader node, XmlNodeType type)
    {
        Int32 count = 0;
        Int32 currentDepth = node.Depth;
        Int32 validDepth = currentDepth + 1;
    
        while (node.Read() && (node.Depth != currentDepth))
        {
            if ((node.NodeType == type) && (node.Depth == validDepth))
                ++count;
        }
    
        return count;
    }