Using .NET XmlSerializer for xml with different polymorphic roots

I have XML docs with different roots coming from one source. I have a XSD schema just like described in this question, with the abstract='true' root element 'BaseElem' of a Base type, plus additional root elements Elem1, Elem2, ... that extend the Base type and use substitutionGroup='BaseElement' attribute.

xsd.exe generates BaseElem and the derived Elem1, Elem2, ... classes ok, with only the derived classes having the [XmlRootAttribute].

I would like to use the built-in XmlSerializer to both serialize and deserialize generated objects.

<Elem1>...</Elem1>  <!--This is the whole document, not a frament-->

    into this object, or in reverse:

var elem1 = new Elem1();

Serializing:

var srz = new XmlSerializer(typeof (BaseElem));
srz.Serialize(writer, elem1);

produces elements. To serialize with specific root, I must create serializer "new XmlSerializer(typeof(Elem1))".

Deserializing does not work at all if the BaseElem is used, and only works like this:

var srz = new XmlSerializer(typeof (Elem1));
var elem1 = (Elem1) srz.Deserialize(reader);

How can I have a more polymorphic, single serializer approach?

Thanks!


if I understand correctly... could you use more of a generic approach? (showing just the deserialization snippet...)

   public static T DeserializeObject<T>(object obj)
    {
       XmlSerializer xs = new XmlSerializer(typeof(T));
       //etc
       return (T)xs.Deserialize(obj);
    }
链接地址: http://www.djcxy.com/p/54904.html

上一篇: 使用XmlSerializer反序列化随机/未知类型

下一篇: 将.NET XmlSerializer用于具有不同多态根的xml