Finding References in IXmlSerializable
I am writing elements of a particular type into the outgoing xml using IXmlSerializable. I have implemented the schema, and am writing the items out. The开发者_开发知识库 code that follows is an example.
public void IXmlSerializable.WriteXml(XmlWriter writer) {
// Write Out Class.
foreach (var item in myItems) {
DataContractSerializer ds = new DataContractSerializer(typeof(MyType));
ds.WriteObject(writer, item);
}
}
The problem I have is that MyType is declared as using references
[DataContract(IsReference = true)]
public class MyType { ...
So when the item has already been written to the xml it needs to be a reference.
How do I know if a reference has already been written to the xml? I am of the opinion that I must just ignore references that I am explicitly not in control of. That way I will make up my own reference id's and reference my own instances.
This is clearly a bad hacked compromise as I am duplicating references that should not be duplicated.
Is there any way to find out what has already been written to see if I can find an id for the item already serialized?
Regards
Craig.
The "IsReference" magic works only for serializations within a single "episode". An episode is a single WriteObject call.
Let's say you were to have a top-level object of some top-level type, like below:
[DC]
class Container
{
[DM]
MyType i1 = new MyType();
[DM]
MyType i2 = i1;;
[DM]
MyType i3 = i1;
}
Now, if you were to serialize an instance of Container via a call to WriteObject, that is when "ids" and "refs" come into play. When i1 gets serialized, it will get serialized with an ID of 1, but when i2 and i3 get serialized, they each get serialized with "REF" attributes pointing back to the ID 1 of MyType.
In your example, because every call to WriteObject is a separate episode, each call will serialize out the whole object graph. Unless you can package all of your different MyType instances into a higher-level object (or even a collection), you're out of luck. So that's what you need to do -- essentially force all instances of MyType to be serialized within a single higher level WriteObject call.
精彩评论