xsi:type deserialization issue

2.3k Views Asked by At

I'm having trouble on deserializing xml node which has xsi:type attribute. Part of the code:

    [XmlElement("ValueObject")]
    public object ValueObject       {
        get 
        {...
        }
        set 
        {...
        }
    }

after serialization

http://imgur.com/uEJ1s

The value could be serialized fine(pictured), but when it was deserialized the ValueObject has no type information but System.Xml.XmlNode[3].

This was on .net fx 4.0, C#

Any ideas why?

Thanks,

1

There are 1 best solutions below

0
On

You have not sent your code, but I would guess that you had not indicated the list of possible derived types, when creating the XmlSerializer. Here is an example that makes use of DateTime and float, as derived types of object, for Value:

using System;
using System.IO;
using System.Xml.Serialization;

public class Test
{
        public class ValueObject
        {
            [XmlElement("Value")] // This XML array does not have a container
            public object[] Values;
            public ValueObject() {}
        }

        static void Main(string[] args)
        {
            ValueObject value1 = new ValueObject();
            value1.Values = new object[] { DateTime.Now, 3.14159f };
            save("test.xml", value1);
            ValueObject value2 = load("test.xml");
        }

        static void save(string filename, ValueObject item)
        {
            XmlSerializer x = new XmlSerializer(typeof(ValueObject), new Type[] { typeof(DateTime), typeof(float) });
            FileStream fs = new FileStream(filename, FileMode.Create);
            x.Serialize(fs, item);
            fs.Close();
        }

        static ValueObject load(string filename)
        {
            XmlSerializer x = new XmlSerializer(typeof(ValueObject), new Type[] { typeof(DateTime), typeof(float) });
            FileStream fs = new FileStream(filename, FileMode.Open);
            ValueObject valueObject = (ValueObject)x.Deserialize(fs);
            fs.Close();
            return valueObject;
        }
}

The XML produced and consumed by this code is:

<?xml version="1.0"?>
<ValueObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Value xsi:type="xsd:dateTime">2011-04-16T00:15:11.5933632+02:00</Value>
  <Value xsi:type="xsd:float">3.14159</Value>
</ValueObject>