Search code examples
c#xmlxmlreader

check if xmlReader is concrete end element


I've got xmlReader set up and can check for certain elements, but I cant find a way to check for a closing element, lets say I want to have another case statement for </perls> tag in addition to its opening one, how could I do this? I know for sure that such tag is not self closing.

using (XmlReader reader = XmlReader.Create("perls.xml"))
{
    while (reader.Read())
    {
    // Only detect start elements.
    if (reader.IsStartElement())
    {
        // Get element name and switch on it.
        switch (reader.Name)
        {
        case "perls":
            // Detect this element.
            Console.WriteLine("Start <perls> element.");
            break;
        case "article":
            // Detect this article element.
            Console.WriteLine("Start <article> element.");
            // Search for the attribute name on this current node.
            string attribute = reader["name"];
            if (attribute != null)
            {
            Console.WriteLine("  Has attribute name: " + attribute);
            }
            // Next read will contain text.
            if (reader.Read())
            {
            Console.WriteLine("  Text node: " + reader.Value.Trim());
            }
            break;
        }
    }
    }
}

Solution

  • How about simply check if NodeType equals XmlNodeType.EndElement, like :

    if (reader.NodeType == XmlNodeType.EndElement)
    {
        ....
    }
    

    For reference : http://www.codingeverything.com/2013/05/extending-xmlreader-class-isendelement.html