Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSerializer and embedded WhiteSpace

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;
           }
like image 991
Noel Avatar asked Sep 03 '10 22:09

Noel


2 Answers

You can use the XmlReader to load the xml with IngoreWhitespace set to false

new XmlSerializer(typeof(Request)).Deserialize(XmlReader.Create(_memoryStream, new XmlReaderSettings { IgnoreWhitespace = false })) as Request;
like image 111
Yitzchok Avatar answered Sep 29 '22 12:09

Yitzchok


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>
like image 39
Ondrej Tucny Avatar answered Sep 29 '22 11:09

Ondrej Tucny