问题
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?
回答1:
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 element1
element.
In the non-indented form, there's no text node, so you're getting the local name of element1
to start with, and when you move to the next element it's reading element2
instead.
If you tell the XmlReader
to ignore irrelevant whitespace, the difference will go away - but you may lose cases where you want the whitespace to be considered relevant.
回答2:
Did you set the value below?
settings.IgnoreWhitespace = true;
[EDIT]
Probably you would like to change the settings
:
XmlReaderSettings settings = new XmlReaderSettings
{
IgnoreComments = true,
//IgnoreWhitespace = false,
IgnoreWhitespace = true,
IgnoreProcessingInstructions = true
};
来源:https://stackoverflow.com/questions/13879378/xmlreader-gives-different-result-when-xml-is-indented