Hi all,
I have a field of type string in a type that is serialized to XML. If the field value is just one space, the resulting XML is this:
<FieldName />
This creates an issue with deserializing, because in the context of the application, " " is not equal to string.Empty.
I've looked for options on the serializer, and for serialization attributes that would control this behavior, but I could not find any.
Any help is appreciated.
SA.
[Edit: changed subject to be more accurate description of the problem.]

XML serializer does not serialize values of properties if value contains only spaces
Chris Ellis
This is not the behavior I see: a single space in an element value persisted just fine.
Here is my test:
public class Data
{
public string str;
}
public class TestMe
{
public static void Main(string[] args)
{
Data data = new Data();
data.str = " ";
new XmlSerializer(typeof(Data)).Serialize(Console.Out, data);
}
}
And the output:
<Data xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<str> </str>
</Data>
Could you post a simplified repro exhibiting erroneous behavior
Thanks,
Elena Kharitidi
NeGRoiDe
Can you share the definition of the XmlObject
Thanks, Elena
BindingDesparation
Please, consider that XML "normalize" whitespaces in the attribute values. (http://www.w3.org/TR/1998/REC-xml-19980210#AVNormalize).
XmlReader may have this feature set on or off but if XmlSerialization sets it on "/t" and "/n" will be converted to " ".
sgopus
Sergey:
Thank you for your answer.
I am not sure I am following your statement entirely. First of all, I am not talking about an attribute value, but rather about an element value. I expected
<FieldName> </FieldName>
not
<FieldName />
I may not have made it clear that this is not in the context of web services, but rather in the context of serialization for persistence of an object in a database.
Thanks,
SA.
sunrunner
Elena, all:
So I figured out that the issue was with SQL Server (the XML string was stored in a xml type field).
I get the field back from SQL Server with the space preserved. However, there are issues then with the deserializer.
Here is my code:
o = (
XmlObject)xs.Deserialize(new StringReader(xfo.XmlField));xfo.XmlField is a string type field which contains this string:
"<XmlObject xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Xml> </Xml></XmlObject>"
The Xml property of the XmlObject after this deserialization contains string.Empty, not " ".
Thanks for any help,
SA.
eli_verbuyst
Elena:
Please see my other post in this forum re StringReader vs XmlTextReader.
Thanks,
SA.
Idgaf
Elena:
Thanks for your reply. Your answer put me on the right path.
It isn't the .NET XmlSerializer that was losing the spaces, it's the SQL Server 2005 xml type field (or the way I store data in it...).
Thanks again,
SA.