views:

30

answers:

3

I have the following xml that contains a white space Field1Value . When I deserialize that xml I lose the single space character. The value of Request.Field2 is "". Is this a bug in the xml serializer? Can anyone recommend a solution/ workaround to keep this space?

  ...
            var encoding = new System.Text.UTF8Encoding();
            var _xmlData = "<Request><Field1>Field1Value</Field1><Field2>   </Field2></Request>";
            var _xmlDataAsByteArray = new byte[_xmlData.Length];
            _xmlDataAsByteArray = encoding.GetBytes(_xmlData);

            var _memoryStream = new MemoryStream(_xmlDataAsByteArray);

           var _XmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Request));

            Request _request = _XmlSerializer.Deserialize(_memoryStream) as Request;

  ...
         public class Request
           {
               public string Field1;
               public string Field2;
           }
A: 

Maybe the xml:space attribute can help by setting it to 'preserve'. See this article as a starting point.

Timores
+1  A: 

No, this is not a bug, but expected behavior. Unless you opt-in for preserving space, XML is processors (i.e. the apps reading and writing XML) are supposed to normalize whitespace. See section 2.1 of the XML 1.1 specification here.

To preserve the whitespace you have to include the xml:space="preserve" attribute. Hence the XML shall look like this:

<Request>
   <Field1>Field1Value</Field1>
   <!-- spaces inside Field2 will be preserved -->
   <Field2 xml:space="preserve">   </Field2> 
</Request>
Ondrej Tucny
A: 

Thanks Ondrej. As our client will be sending in the xml we have no control over this. So to preserve space see solution link text