Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic XML serialization/deserialization

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

like image 816
Andrey Avatar asked Oct 19 '25 16:10

Andrey


2 Answers

Try XmlArrayItem with XmlSerializer:

public class X
{        
     [XmlArrayItem(typeof(D)),
      XmlArrayItem(typeof(B))]
     public B[] Col { get; set; }
}
like image 147
Dmitry Ornatsky Avatar answered Oct 21 '25 07:10

Dmitry Ornatsky


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; } 
} 
like image 45
JaredPar Avatar answered Oct 21 '25 06:10

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!