Hi
First, some background - I faced today a problem with serializing entities with nullable properties (using types from Nullables library from NhibernateContrib). The symptom is simple - properties of Nullable types are serialized always as empty xml nodes, regardless of Hasvalue value.
e.g. class "test" with two properties t2 (Int32) and t1 (NullableInt32) is serialized into something like :
Code:
<?xml version="1.0"?>
<test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<t1 />
<t2>10</t2>
</test>
I've done some investigation and now I know that XmlSerializer skips everything but public read-write properties. So I solved the problem by adding to each Nullable class public read-write property "V" of the string type , using XmlConvert methods to format the value for serialization in the getter and extracting it during deserialization in the setter:
Code:
class NullableInt32 ....
public String V
{
get
{
if (hasValue)
return XmlConvert.ToString(_value);
else
return "";
}
set
{
if (value=="")
{
hasValue=false;
}
else
{
_value=XmlConvert.ToInt32(value);
hasValue=true;
}
}
}
...
...and so on with other nullables
After a little mess with strong names and references I successed, with the following xml as a result:
Code:
<?xml version="1.0"?>
<test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<t1>
<V>12</V>
</t1>
<t2>10</t2>
</test>
Now my questions.
- I wonder if it is the right way to do XmlSerialization with Nullables - maybe is there is a simple way I am missing (I'm not feeling comfortable by spoiling those great libs with my code :) ).
- And finaly, if it is the only (and right) way, maybe it is a good idea to implement this simple change into Nullables to allow XmlSerialization (I belive people using WebServices may need it)?