Arpit Khandelwal
Arpit Khandelwal

Reputation: 1803

Is It possible to perform serialization with circular references?

So, my entity class (written in C#) follows a parent child model where every child object must have a Parent property in which it keeps reference of its Parent.

This Parent property causes issues in serialization of the Object due to circular references.

I can't remove the reference to parent, neither I can mark it XmlIgnore (since I need to read it back when I deserialize the XML)

Any ideas on this?

Upvotes: 15

Views: 8573

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292405

XML serialization doesn't support circular references, you need to exclude the parent property from the serialization using the XmlIgnore attribute. See this blog post for a way to maintain the relationship when you deserialize.

Alternatively, you could use DataContractSerializer instead of XmlSerializer. It supports circular references, but doesn't provide much control over the XML schema...

Upvotes: 12

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

You can either create your own XMLSerializer or use the DataContractSerializer and the [DataContract(IsReference= true)] attribute to tell the serializer to remember the references.

Upvotes: 11

Related Questions