Problem with XmlReader.IsEmptyElement property

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I was doing some basic XML processing with XmlReader class (in VisualStudio 2005 Beta 2). The code was supposed to fire events when it encounters either start or end of an XML element. According to .Net documentation the XmlReader does not explicitly read XmlNodeType.EndElement for empty elements (i.e. ones ending with />) - we are supposed to check the value of IsEmptyElement property to detect the end of empty XML elements.
This indeed works for empty elements with NO ATTRIBUTES such as <myelement/>.
But it does not seem to work for empty elements WITH attributes. For instance for this element:

<myelement attr1="value"/>

the XmlReader does not read the end of element (as expected) but IsEmptyElement property is false as if its a regular element! So is it a bug? How are we supposed to detect the end of such elements?

The following is the skeleleton of the test code (in J#):

XmlReader = ... // get the reader
while (reader.Read())
{
XmlNodeType nodeType = reader.get_NodeType();

switch (nodeType)
{
case XmlNodeType.Element:
// fire StartElement event
....
// special case: if we encounter an empty element (such as <element/>)
// then the XMLReader will not read the closing tag for it,
// i.e. XmlNodeType.EndElement will not work
// instead we need to check explicitly if the element is empty and if it is
// then fire endElement SAX event
if (reader.get_IsEmptyElement())
{
// fire EndElement event
}
break;
case XmlNodeType.EndElement:
// fire EndElement event
break;
// other cases
}



View the full article
 
Back
Top