Skip to main content

How do I know that an XML element is empty?

Imagine that you have the following XML:

   1:  <books>
   2:     <book />
   3:     <book></book>
   4:  <books>

How do you know the difference between line 2 and 3 when parsing the XML? (And yes there is a difference. Go read the XML specifications!)

The IsEmptyElement property on the XMLReader class gives you this specific functionality.

   1:  while (reader.Read()) {
   2:    if (reader.IsStartElement()) {
   3:      if (reader.IsEmptyElement)
   4:        Console.WriteLine("<{0}/>", reader.Name);
   5:      }
   6:    } 
   7:  }