tags:

views:

511

answers:

2

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.

+1  A: 

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.

eglasius
+3  A: 

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.)

Cerebrus
+1 agree with all - on a side note I just learned on another question/answer you can use xpath with linq2sql: http://msdn.microsoft.com/en-us/library/bb342176.aspx
eglasius