Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/877157/what-is-an-object-graph-and-how-do-i-serialize-one

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
121 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:

  • A (knows that B is its child)
    • B (knows that A is its parent)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...