Search code examples
.netrecursionserializationdata-structuresdatacontractserializer

.net DataContractSerializer: how to handle recursive data structures?


If I have a class with a recursive data structure like this

  public class Test
  {
     public string Name { get; set; }
     public Test Recursion { get; set; }
  }

and serialize it

     var objectToSave= new Test{Name="Parent"};
     objectToSave.Recursion = test; // this is an endless recursion

     DataContractSerializer ds = new DataContractSerializer(objectToSave.GetType());

     XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
     using (XmlWriter w = XmlWriter.Create("result.xml", settings))
        ds.WriteObject(w, objectToSave);

i get

    <?xml version="1.0" encoding="utf-8"?>
    <MyNamespace.Test ...>
      <Name>Parent</Name>
      <Recursion>
        <Name>Parent</Name>
        <Recursion>
          <Name>Parent</Name>
          <Recursion>
            <Name>Parent</Name>
            <Recursion>
           ...... togehter 1586 lines

update: There is a parameter MaxItemsInObjectGraph to limit the output.

Does anybody know how to find out a good value for this?

Or is there a way to tell the serializer how deep recursion should go or to get a more compact xml without redundance?


Solution

  • this setting seems to work

         DataContractSerializer ds = new DataContractSerializer(objectToSave.GetType(), 
                                         null, 20000, true, true, null);
    

    Result

        <MyNamespace.Test ...>
          <Name z:Id="2">Parent</Name>
          <Recursion z:Ref="1" i:nil="true" />
        </MyNamespace.Test>