I have the same XML in two different files.
In one file the XML is indented – the other not.
The XML is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<test>
<element1></element1>
<element2></element2>
<element3></element3>
</test>
When using the following code I get different result with the two files:
XmlReaderSettings settings = new XmlReaderSettings
{
IgnoreComments = true,
IgnoreWhitespace = false,
IgnoreProcessingInstructions = true
};
using (XmlReader reader = XmlReader.Create(invoiceStream, settings))
{
reader.MoveToContent();
reader.Read();
var prevLocalname = reader.LocalName;
var element = XNode.ReadFrom(reader) as XElement;
var newLocalname = reader.LocalName;
}
With the indented file I get the following values:
prevLocalname = "";
newLocalname = "element1";
With the file not indented I get the following values:
prevLocalname = "element1";
newLocalname = "element2";
Can anyone explain this?
Sure – in the indented form, you’ve got a text node which you’re getting the local name of (as empty). You’re then moving to the next node, which is the
element1element.In the non-indented form, there’s no text node, so you’re getting the local name of
element1to start with, and when you move to the next element it’s readingelement2instead.If you tell the
XmlReaderto ignore irrelevant whitespace, the difference will go away – but you may lose cases where you want the whitespace to be considered relevant.