Friday, December 29, 2006

Lost in Space

While using XmlSerializer in .NET 2.0, I found that spaces in my string values are lost during a round-trip of serialization and de-serialization. Looking at the serialized XML string, I can find that space is preserved during serialization. The XML looks like this:
<Text> </Text>


But after de-serialization the string variable Text only has value string.Empty. After a little research, I found that using the following code segment to de-serialize can avoid the above problem:

//variable xmlString contains the XML string to be de-serialized.
//varialbe result of type T is to be de-serialized from the string
T result;
XmlSerializer s = new XmlSerializer(typeof(T));
StringReader r = new StringReader(xmlString);
XmlReaderSettings settings = new XmlReaderSettings();
//white space are especially important for string types
//if "IgnoreWhitespace" is true, a string value equal to " "
//may be lost during serialization and deserialization.
//the line below is the key of this posting
settings.IgnoreWhitespace = false;
XmlReader reader = XmlReader.Create(r, settings);
result = (T)s.Deserialize(reader);


For comparison, below is my old de-serialization code that causes lost of space:

//variable xmlString contains the XML string to be de-serialized.
//varialbe result of type T is to be de-serialized from the string
T result;
XmlSerializer s = new XmlSerializer(typeof(T));
StringReader r = new StringReader(xmlString);
result = (T)s.Deserialize(r);

No comments: