Hi
I've been reading lately about serialization. I've read that when I use XmlSerialization I cannot serialize object graphs. What is an object graph and why I cannot serialize it simply?
Kind Regards PK
Hi
I've been reading lately about serialization. I've read that when I use XmlSerialization I cannot serialize object graphs. What is an object graph and why I cannot serialize it simply?
Kind Regards PK
An object graph is not a single object, but rather a set of related objects. For a simple example, consider:
public class Node {
public string Name {...}
public Node Parent {...}
public List<Node> Children {...}
}
where each child knows about the parent (and the parent knows about the child).
The problem is that xml is a tree based on object properties... and it wants to just walk them - i.e. with the simple parent/child:
that would serialize as:
<Node>
<Name>A</Name>
<!-- no Parent as A is the top node, so null -->
<Children>
<Node>
<Name>B</Name>
<Parent>
<Node>
<Name>A</Name>
*** boom ***
You can see that we got back to A, so we're now in an endless loop.
XmlSerializer
can serialize trees of data, but not full graphs. You can mark properties to be ignored, for example:
[XmlIgnore]
public Node Parent {...}
And now it'll work, but we'll have to fix the Parent
afterwards.
By contrast, some other serializers can handle graphs (DataContractSerializer
can on-demand). It does this by tracking objects against a unique key - but then the output isn't what you expect from regular xml.
An object graph is a set of objects that reference one another.
Serializing an object graph is tricky. The serializer would have to assign a unique ID to every object and then replace references with unique IDs.
If it was serializing in XML format, and handling object graphs, it would have to add an "OBJECT_ID" (or some other named) attribute to every element. This would be very easy to break: what would happen if you added a property with the same name to the class you are serializing?
The simplest solution is to not support it.
.NET provides binary serialization which deals with this issue as well as the issue of circular references.
A general object graph consists of a set of object holding references to each other. If you have an object tree where there are no backwards links, serialization and deserialization is simple. With a general graph, the (de)serialization process needs to keep track of the identity of each object, and use some form of mark-and-sweep algorithm to ensure that objects aren't (de)serialized twice.
Is there no library or function which can do this? Create xml of object graph?