37

I am using XmlReader in .NET to parse an XML file using a loop:

while (xml.Read()) {
   switch xml.NodeType {
     case XmlNodeType.Element:
      //Do something
     case XmlNodeType.Text:
      //Do something
     case XmlNodeType.EndElement:  
      //Do something
   }
}

I was wondering if it was normal that the following XML code does not produce some EndElement nodes? Please note the missing space before the /> but I don't think that's the problem.

<date month="November" year="2001"/>
<zone name="xml"/>

Is there a different NodeType or property to indicate a self-closing element?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Vincent
  • 22,366
  • 18
  • 58
  • 61

1 Answers1

61

No, you check it by looking at XmlReader.IsEmptyElement.

In the docs for that property:

A corresponding EndElement node is not generated for empty elements.

ESV
  • 7,620
  • 4
  • 39
  • 29
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    How would I tell the difference between `` and `` when my current `NodeType` is `StartElement`? `IsEmptyElement` is `true` for both scenarios. – Brian Warshaw Aug 15 '16 at 17:52
  • @BrianWarshaw: You'd see whether an `EndElement` node is present, basically... I don't know any way of doing it immediately when you're on the `StartElement`. – Jon Skeet Aug 15 '16 at 18:02
  • 1
    Thanks--turns out I may have been wrong about `IsEmptyElement` being true in those cases. I've been staring at this output for too long :-) – Brian Warshaw Aug 15 '16 at 18:09