tags:

views:

201

answers:

2

If I skip, do I still need to read the end element?

            reader.ReadStartElement("ENCODING");
            reader.Skip();
            reader.ReadEndElement();

And I don't get when we need to ReadEndElement. For example we've gotten by in some of our classes with not using it at all. For example:

        using (reader)
        {
            reader.Read();
            reader.ReadStartElement("Envelope");
            reader.ReadStartElement("Body");
            reader.ReadStartElement("RESULT");
            reader.ReadStartElement("SUCCESS");
             _success = reader.ReadString();
            if (!Success)
            {
                if (SomeUtil.ReadUntilElement(reader, "FaultString"))
                {
                    string _errorMessage = reader.ReadString();
                    InvalidOperationException ex = new InvalidOperationException(_errorMessage);

                    throw ex;
                }
                else
                    throw new InvalidOperationException("Invalid Error Message");
            }
        }
A: 

You need to match the number of times you call ReadStartElement with the same number of calls to ReadEndElement. It might actually work in some cases when you are at the last elements but in general it is not recommended.

Darin Dimitrov
My boss said we don't need them at all! and it works! I started out matching them and then he said we don't need all of them. wtf. So that's why I was asking because I can't see why it would work without them but it does.
CoffeeAddict
A: 

You can skip the current element by doing roughly the following:

  int depth = reader.Depth;
  while (!reader.EOF && (reader.Depth > depth || reader.NodeType == XmlNodeType.EndElement))
   reader.Read();

By capturing and comparing the depth of the reader we can be sure we found the matching close of the current element.

csharptest.net