I've got a class which contains a number of resources which are loaded from files. Want to serialize objects of this class to XML but with paths to the resources instead of the actual resources themselves.
Right now I have got around this by creating a number of ResourceSource
fields which store the path to the resource and using XMLIgnore
on the resources themselves. However, these have to be public which isn't so good.
It would seem that what I really want is to be able to creat开发者_Python百科e special property accessors which are only executed by XMLSerialize. Does this feature exist or is there a way I might be able to implement it?
Alternatively, can I set my ResourceSource
fields to be accessible only by XMLSerialize?
Have you looked at implementing IXmlSerializable instead? This allows you finer grained control over the serialization process.
There are two reasons to implement this interface. The first is to control how your object is serialized or deserialized by the XmlSerializer. For example, you can chunk data into bytes instead of buffering large data sets, and also avoid the inflation that occurs when the data is encoded using Base64 encoding. To control the serialization, implement the ReadXml and WriteXml methods to control the XmlReader and XmlWriter classes used to read and write the XML.
The second reason is to be able to control the schema. To enable this, you must apply the XmlSchemaProviderAttribute to the serializable type, and specify the name of the static member that returns the schema.
It sounds like your class is being overloaded to have multiple responsibilities, which is almost always a red flag that it's time for some refactoring.
What I would do is have one serializable class that stores the resource paths and another that stores the resources themselves. The constructor for the non-serializable class could take an instance of the serialized class, load the resources from disk, etc.
精彩评论