开发者

Using .NET XmlSerializer for xml with different polymorphic roots

开发者 https://www.devze.com 2023-01-22 16:08 出处:网络
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 additio

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 o开发者_运维问答bjects.

<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);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号