Monday, April 25, 2011

'Element' is an invalid XmlNodeType

I don't get this. I really don't get the ReadEndElement. I assume after every ReadStartElement, you need to close off the reader to advanced to the next start element and if there's no more start elements, close by ReadEndElement for all other elements?

Sample of the returned XML:

<Envelope>
<Body>
<RESULT>
<SUCCESS>true</SUCCESS>
<SESSIONID>dc302149861088513512481</SESSIONID>
<ENCODING>dc302149861088513512481
</ENCODING>
</RESULT>
</Body>
</Envelope>

           reader.Read();
            reader.ReadStartElement("Envelope");
            reader.ReadStartElement("Body");
            reader.ReadStartElement("RESULT");
            reader.ReadStartElement("SUCCESS");
            reader.ReadEndElement();
            reader.ReadStartElement("SESSIONID");
            _sessionID = reader.ReadString();
            reader.ReadEndElement();
            reader.ReadEndElement(); <-- error here
            reader.ReadEndElement();
            reader.ReadEndElement();

I am ignoring one of the elements (ENCODING) retuned, because I don't need it...not sure if that has anything to do with it. Maybe I'm required to read every element regardless if I want to use it or not.

From stackoverflow
  • You have to read every node (attribute, element, ...) in the document.

    If the reader is positioned on an element, you may skip it (and all its subnodes) with XmlReader.Skip.

    : thanks I actually added back in the missing element. But I just can't understand the # of ReadEndElements I need. Seems like last time in another class I needed one less ReadEndElement than the # of ReadStartElements...almost like you don't need an ReadEndElement for the first ReadStartElement.
    : I mean I've looked at the definition on MSDN which is poor. Because it's saying ReadStartElement and ReadEndElement both move you to the next node. I assume though just by the pure name of "ReadEndElement" that it seals off the current element you're reading. But still I get that error even so
    : so you must do either a reader.ReadString. But as for the ReadEndElement, I assume you must have that for every ReadStartElement to seal off.

0 comments:

Post a Comment