Polymorphic XML serialization/deserialization

情到浓时终转凉″ 提交于 2019-12-13 12:11:54

问题


I have:

public class B     
{
    public string Some { get; set; }
}

public class D : B
{
    public string More { get; set; }
}

[KnownType(typeof(D))]
public class X
{        
    public B[] Col { get; set; }
}

I want to automatically read/write XML exactly like:

<X>
 <Col>
  <B Some="val1" />
  <D Some="val2" More="val3" />
 </Col>
</X>

Neither XmlSerializer not DataContractSerializer helped me. This XML structure is mandatory.

So question is: can this be achieved or i have to parse that XML manually?

Thanks, Andrey


回答1:


Try XmlArrayItem with XmlSerializer:

public class X
{        
     [XmlArrayItem(typeof(D)),
      XmlArrayItem(typeof(B))]
     public B[] Col { get; set; }
}



回答2:


It sounds like you're having trouble serializing the collection portion of the object. When serializing a collection in XML which can contain derived types, you need to inform the serializer about all of the derived types which could appear in the collection with the XmlInclude attribute

[KnownType(typeof(D))] 
public class X 
{ 
  [XmlInclude(Type=typeof(B))]
  [XmlInclude(Type=typeof(D))]        
  public B[] Col { get; set; } 
} 


来源:https://stackoverflow.com/questions/4071639/polymorphic-xml-serialization-deserialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!