Friday, March 2, 2012

WCF: Whitespace after ampersand disappears

We noticed a strange problem when trying to read the contents of an WCF Message into an XmlDocument. The contents of the message body looks like this:
<Customer> 
    <Name>Laurel &amp; Hardy</Name> 
</Customer> 

The code for the reader looks like this:

XmlDocument bodyDoc = new XmlDocument();
bodyDoc.Load(message.GetReaderAtBodyContents());
XmlReaderSettings settings = new XmlReaderSettings();
XmlReader r = XmlReader.Create(new XmlNodeReader(bodyDoc), settings);

However after saving the results into the database, we’ll see the following information:
<Customer> 
    <Name>Laurel &Hardy</Name> 
</Customer> 

So we lost a whitespace after the ampersand.

The solution is to change the XmlDocument properties and add the PreserveWhitespace option:

XmlDocument bodyDoc = new XmlDocument() { PreserveWhitespace = true };