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;
}
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;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With