Tim
Tim

Reputation: 952

How to check if an element tag is end element

For example, I have the following type of condition:

if (reader.IsStartElement("element1"))
{
    while (true)
    {
        if (reader.IsStartElement("element2"))
        {
            // Doing stuff
            reader.ReadEndElement(); //closes element2 tag
        }
        else if (reader.IsStartElement("element3"))
        {
           // Doing stuff
           reader.ReadEndElement(); //closes element3 tag
        }
        else if ((!reader.IsStartElement("element2")) 
                && (!reader.IsStartElement("element3")) 
                && (!reader.IsEndElement("element1"))) // THIS IS MY ISSUE
        {
           throw new XmlException("exception");
        }
        else
        {
           reader.ReadEndElement(); //closes element1 tag
        }    
    }
}

My xml is written in the following type of format:

<element1>
    <element2>
    </element2>
    <element3>
    </element3>
</element1>

What I want to do is say if there is an element being read inside of element1 that is not element2 or element3 and is not the ending element tag for element1 then throw the exception that I have written. The problem is that there is no method for checking an end element tag for XmlReader that I can find. I can check reader.IsStartElement but not reader.IsEndElement. Is there another way I can check if the type is end element?

Upvotes: 3

Views: 4151

Answers (2)

devlin carnate
devlin carnate

Reputation: 8590

You can check for the NodeType, and then verify it's the end tag for element1 using reader.Name

if (reader.NodeType == XmlNodeType.EndElement)
{
    if(reader.Name == "element1")
    {
        //it's element1 end tag
    }
    else
    {
       //it's the end tag for something else
    }
}

Upvotes: 5

JLRishe
JLRishe

Reputation: 101700

You should use reader.Read() to move through the XML, and look at the reader's NodeType.

The XmlNodeType enumeration contains values for both Element and EndElement.

Upvotes: 2

Related Questions