I’ve got a class that when serialized to XML looks like this (generalized for simplicity):
<root>
<resources>
<resource name="foo" anotherattribute="value">data</resource>
<resource name="bar" anotherattribute="value">more data</resource>
</resource>
<myobject name="objName">
<resource name="foo" />
</myobject>
</root>
When it’s deserialized, I need the instance of resource referenced in the property of the myobject instance to be the same object created during the deserialization of the resources collection. Also, if possible I don’t want to have to output the full serialization of the resource instance in myobject, only the name.
Is there any way of doing this? Right now I’m considering resorting to having a separate string property for serialization purposes that gets the relevant object from root when the deserializer sets the property, but that means giving myobject a reference to the root that contains it, and I was hoping to avoid that coupling.
You can’t do that with
XmlSerializer, because it doesn’t handle object references.If you don’t have any constraint on the generated schema, you could use
DataContractSerializer, which also serializes to XML but supports references. To useDataContractSerializer, each type must have aDataContractattribute, and each member you want to serialize must have aDataMemberattribute :Note the
IsReference = truefor theresourceclass: that’s what makes the serializer handle this class by reference. In the generated XML, eachresourceinstance is only serialized once: