I want to make my own xml-serializer class because I need other formatting than the System.Xml.Serialization.XmlSerializer does. My idea is to treat properties of primitive type (such as Integer, Double, String) as XmlAttributes.
To properly implement a usable Xml-Serialization I need to know which variables point to the same object (the binary serialization behaves this way). Because one object should be serialized only once in order that the connections don't get lost. On the side of XmlSerialisation I have the idea to insert a path to the class as a special XmlAttribute.
Do you have tipps for me how to handle such a situation?
### EDITThanks for the answers.
XmlAttributeAttribute is maybe more work than writing my own Serializer because only variables of primitive types (and there are many of them) should be serialized as XmlAttributes. Making a mistake there is more horrible then. I would use a kind of Hashing solution (of course) so far so good. But my idea was to reduce the work of this hashing solution, if I could make sure the object is r开发者_StackOverflow社区eferenced only once. Do you have links to such a question?You can store references within the serializer, as part of the serialization process. When you come to a reference you need to serialize, look through the references you've already serialized - if you find it, output an appropriate ID (or whatever) so you can restore the reference appropriately on deserialization. If not, serialize the object and remember the reference (and associated ID) so that you can spot it if the same reference is used elsewhere in the tree.
On the other hand, I would try hard to work with the built-in serializer before coming up with your own one. For example, to store values in attributes, you can use [XmlAttributeAttribute]
.
You don't need to count the number of variables that point to each object to serialize each object only once.
Instead you can keep a list of the objects you have already serialized and for each new object you can check whether it already exists in that list. How you compare objects is up to you - for example, you could use Equals
or you could compare object references.
If you decide to use Equals
then you will be able to get better performance as you can store the objects in a HashSet.
You can use a Hashtable
of objects and make sure your object is serialised once. You can keep XML representation of the object in the value. Then you need to use XML's ref
in order to reload it once.
Generally object.ReferenceEquals(o1, o2)
will tell you if the objects are the same.
To be honest, I do not want to be in your shoes. It is a lot of work and I am not sure creating a from-scratch serialiser is the way to go.
精彩评论