C #: xml serialization of nodes with circular references

I have a Node class something like this:

class Node { IEnumerable<Node> inputs; } 

Which basically defines a simple graph. I want to serialize my graph in a human-friendly form, so usually I would say xml would be a way. But XML was not done with circular dependencies :)

So - what would be the best way to serialize my chart?

I can come up with several ways:

  • ditch XML, create your own format.
  • use XML, mark each Node with a unique identifier, keep connection lists separate from nodes, and allow after loading

But I think that other people must have had the same problem, so there may be some better options. Does anyone know of a solid approach?

+6
c # xml serialization hyperlink
source share
2 answers

For xml, I would go with the id approach (changing the DTO model so that it is not cyclic).

Note that the DataContractSerializer can automatically support cyclic object graphics by passing true for the preserveObjectReferences parameter in overloaded constructors; it will not be as simple as the output of the XmlSerializer , but it will still be readable.

+3
source share

If you switch to WCF DataContractSerializer, you can save references to objects (in 3.5 SP 1 and later)

 [DataContract(IsReference=true)] 

Sowmy has a good record here

+1
source share

All Articles