Tuesday, September 27, 2011

Parse XML with XmlReader (closing empty elements correctly)

If you want to parse an XML document with the XmlReader, it might help to use this XmlReader example from MSDN. However, there's one thing missing: If you parse an XML with empty elements, such as:
<example1 />
<example2>bla</example2>


the example doesn't set the closing tags write, but like this:
<example1>
 <example2>bla</example2>
</example1>


In order to omit this problem, you have to write the end elements in case that the reader parses an empty element:
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
writer.WriteAttributes(reader, true);
if (reader.IsEmptyElement)
 writer.WriteEndElement();
break;

No comments: