user72603
user72603

Reputation: 997

Matching ReadEndElement with ReadStartElement when using an XmlReader

My question is simple. I've been using ReadStartElement and ReadEndElement with the XmlReader in my code just fine. The question is (and this is after looking at MSDN), do you need to match the two?

In other words, do I end with ReadEndElement for each and every ReadStartElement or is are there cases where you don't need so many ReadEndElement calls in your code when reading an XML Envelop? Thee have been cases where I did not always have a matching ReadEndElement and reading the xml worked fine.

Upvotes: 1

Views: 1831

Answers (2)

Cerebrus
Cerebrus

Reputation: 25775

Yes, I believe you do need to match them most often. This is because both the ReadStartElement and ReadEndElement move the XmlReader to the next node. However, they check for different things.

This unnecessarily added verbosity in the code is just one reason I always prefer to navigate XML using an XPathNavigator. It's convenience is simply unmatched (unless you compare it with LINQ.)

Upvotes: 3

eglasius
eglasius

Reputation: 36037

I don't think it is a good idea to not put then in the code. You can get into trouble with certain xml element hierachies depending on which one you miss. Maybe only the last elements.

That said, I use linq 2 xml instead, so I don't have to deal with this :) You can load a reader on XElement.Load, and work with it in a cleaner way.

Upvotes: 1

Related Questions