serialize multiple reference objects with XmlSerialize

235 views Asked by At

what is the best way to serialize with XmlSerialize classes with cross reference?

In the example below multiple B classes can point to the same A object. How do I serialize C without writing multiple A in the xml? My classes are big so I prefer using automatic serialization and not writing a complete

public class A{
  int id;
}

public class B{
  int id;
  A a;
}

public class Root{
  B[] bArray;
}
2

There are 2 answers

0
jdweng On

Should not make any difference that the classes are looped.

    [XmlRoot("A")]
    public class A
    {
        [XmlElement("id")]
        int id;
    }
    [XmlRoot("B")]
    public class B
    {
        [XmlElement("id")]
        int id;
        [XmlElement("A")]
        A a;
    }
    [XmlRoot("Root")]
    public class Root
    {
        [XmlElement("B")]
        List<B> bArray;
    }
​
0
afeygin On

XmlSerializer cannot handle cross references. Try using DataContractSerializer with PreserveObjectReferences = true.