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:
    <Name>Laurel &amp; Hardy</Name> 

The code for the reader looks like this:

XmlDocument bodyDoc = new XmlDocument();
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:
    <Name>Laurel &Hardy</Name> 

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 };