Search code examples
c#xmlxmlreader

Why does XmlReader.IsEmptyElement return different values?


I have the next simple xml file:

<?xml version="1.0" encoding="UTF-8" ?><work><pageSetup paperSize="9" fitToHeight="0" orientation="landscape"></pageSetup></work>

When I run the next code:

using (XmlReader reader = XmlReader.Create(inFile))
    while (reader.Read())
        Console.WriteLine("Name = {0}, NodeType = {1}, IsEmptyElement ={2}\n", reader.Name, reader.NodeType, reader.IsEmptyElement);

The output is:

Name = xml, NodeType = XmlDeclaration, IsEmptyElement =False

Name = work, NodeType = Element, IsEmptyElement =False

Name = pageSetup, NodeType = Element, IsEmptyElement =False

Name = pageSetup, NodeType = EndElement, IsEmptyElement =False

Name = work, NodeType = EndElement, IsEmptyElement =False


As you can see pageSetup's IsEmptyElement=False (I don't know why... see https://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.isemptyelement.aspx)

But if I foramt the xml (ctrl+alt+shift+b in Notepad++) which becomes with line breaks:

<?xml version="1.0" encoding="UTF-8" ?>
<work>
    <pageSetup paperSize="9" fitToHeight="0" orientation="landscape"/>
</work>

And run the program, the output is:

Name = xml, NodeType = XmlDeclaration, IsEmptyElement =False

Name = , NodeType = Whitespace, IsEmptyElement =False

Name = work, NodeType = Element, IsEmptyElement =False

Name = , NodeType = Whitespace, IsEmptyElement =False

Name = pageSetup, NodeType = Element, IsEmptyElement =True

Name = , NodeType = Whitespace, IsEmptyElement =False

Name = work,NodeType = EndElement, IsEmptyElement =False


As you can see pageSetup's IsEmptyElement=True

Why is there a different (in pageSetup's IsEmptyElement value) between the two xml files?


Solution

  • According to MSDN, IsEmptyElement simply reports whether or not the element in the source document had an end element tag.

    In the first case, you have have an end element so IsEmptyElement returns false (although element content is empty), where as in second case you have no end tag which is why you see IsEmptyElement set to true.