Tomtom
Tomtom

Reputation: 9394

XML Serialization Circular Reference

In my application I use the following code to serialze objects:

    private static string Serialize(Type type, object objectToSerialize)
    {
        StringBuilder builder = new StringBuilder();
        using (TextWriter writer = new StringWriter(builder))
        {
            XmlSerializer serializer = new XmlSerializer(type);
            serializer.Serialize(writer, objectToSerialize);
        }
        return builder.ToString();
    }

This code just worked fine until now.

We've introduced a new class which looks like:

    [Serializable]
    public class Restriction 
    {
        public string Id { get; set; }
        public ResticType Type { get; set; }
        public Restriction Parent { get; set; }
        public List<Restriction> Children { get; set; }  
    }

If I try to serialize it I get the following exception:

A circular reference was detected while serializing an object of type Restriction

I already found out, that this occures because of the Parent and the Children which are also of type Restriction

I've already tried to set the Parent-Property to NonSerialized but this doesn't work.

Unfortunately I can not change the code for serialization...

What can I do to serialize this class?

Actual my only idea is to implement IXmlSerializable in my Restriction-class and do the reading and writing of the xml by my own. I hope there is another way...

Upvotes: 1

Views: 187

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292405

I've already tried to set the Parent-Property to NonSerialized but this doesn't work.

NonSerialized is for binary serialization. Use XmlIgnore instead.

Note that you'll have to manually restore the Parent property after deserialization:

void RestoreParentRelationship(Restriction restriction)
{
    foreach (var child in restriction.Children)
        child.Parent = restriction;
}

Upvotes: 2

Related Questions