-->

XmlReader chopping off whitespace after ampersand

2019-07-04 12:44发布

问题:

This is strange. I've got a WCF Message and I'm trying to read the contents of the body into an XmlDocument. The contents of the message body look like this on the wire (when inspected with WCF tracing turned on):

<abc>
    <timeZone>(GMT-05:00) Eastern Time (US &amp; Canada)</timeZone>
</abc>

The code for the reader looks like this:

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = false;
settings.CheckCharacters = false;
XmlReader bodyReader = XmlReader.Create(
        message.GetReaderAtBodyContents().ReadSubtree(), settings);
XmlDocument messageDoc = new XmlDocument();
messageDoc.Load(bodyReader);

The resulting XML in messageDoc looks like this:

<abc>
    <timeZone>(GMT-05:00) Eastern Time (US &Canada)</timeZone>
</abc>

So where did the extra whitespace after the original &amp; go?

回答1:

You can simplify the code by removing the XmlReader. Then set the PreserveWhiteSpace on the XmlDocument. You can replace all of your code with:

XmlDocument messageDoc = new XmlDocument() { PreserveWhitespace = true };
messageDoc.Load(message.GetReaderAtBodyContents().ReadSubtree());