Reputation: 10919
I am using the .NET XmlSerializer
class to write an XML string to a StringWriter (not WCF or JSON or anything else that involves services).
After hours of trying to find out why I was getting the exception of There was an error generating the XML document
after calling XmlSerializer.Serialize()
, I finally discovered that it involved a circular reference. My classes look like this:
class Table
{
public List<Columns> Columns {get; set;}
}
class Column
{
public Table Table {get; set;}
}
As you can see, a table has a collection of columns, but each column in that collection also holds a reference to its parent table.
I do not want to ignore the property during serialization. I want to be able to deserialize it and not have to rebuild references. Back when I was using WCF, there was a method to preserve references across the wire to reduce the size of the XML. Certainly .NET offers some similar method of serializing circular relationships to XML without compromising the integrity of the XML itself.
Upvotes: 2
Views: 894
Reputation: 1062745
No, XmlSerializer
does not support this. You mention WCF: WCF doesn't really use XmlSerializer
(unless your type is clearly marked for such) - it prefers to use DataContractSerializer
, and DataContractSerializer
can support circular references, but only be enabling a flag at construction:
var serializer = new DataContractSerializer(typeof(Foo),
new DataContractSerializerSettings
{
PreserveObjectReferences = true
});
Note that DataContractSerializerSettings
is only in .NET 4.5 and above; prior to that, the same is also available on a constructor overload (the preserveObjectReferences
parameter).
Note that XmlSerializer
and DataContractSerializer
are not 1:1 compatible; they behave differently in many subtle ways.
Upvotes: 4