Wednesday, August 18, 2010

Getting an XmlNode (or XmlElement) Out of XPathNodeIterator (C#)

Symptom:

You have a code you iterate through a group of Xml Nodes (for most people that's XmlElement). You have however noticed that once you get to a specific spot, there is no easy way to perform the complete node operations against the iterator since Casting of the iterator to XmlElement results in a compilation error.

So, you cannot cast the Current of the iterator like

XmlNode node = (XmlNode) i.Current;

(I really think this is a poor design myself since it goes against all our intuition.)

Solution:

Well, there actually is a way to "cast" this to an element, but the syntax is a bit more involved.

XmlNode node = ((IHasXmlNode) i.Current).GetNode();

Or in most cases you can cast this to XmlElement by

XmlElement node = (XmlElement) ((IHasXmlNode) i.Current).GetNode();

Post a Comment