开发者

Add new XML elements and still read older versions of an XML document

In version 1 of my application I have an XML document that looks like this:

<settings>
  <background>black</background>
</settings>

With an element that I serialize and deserialize like this:

[XmlElement("background")]
public string XMLbackground {
    get { return backgroundcolor; }
    set { backgroundcolor = value; }
}

But now in version 2 I want to add new sub-elements to the background element:

<settings>
  <background>
    <color>black</color>
    <angle>62</angle>
  </background>
</settings>

Which means the background element is no longer a string but a class.

[XmlElement("background")]
public BackgroundSettings background = new BackgroundSettings();

//...

public class BackgroundSettings
{

[XmlElement("color")]
public string XMLcolor {
    get { return backgroundcolor; }
    set { backgroundcolor = value; }
}

[XmlElement("angle")]
public string XMLangle {
    get { return backgroundangle; }
    set { backgroundangle = value; }
    }
}

How do I continue to read the version 1 XML document with th开发者_开发百科e same code that now creates and reads the version 2 format using standard .NET serialization markup?


I would say it is a good idea to add "version=x" to the root of the document and check this before deserializing. Then, you have to keep two versions of the data objects in your code - ConfigV1 and ConfigV2. Based on the value of "version=x", deserialize the xml into a ConfigV1 or ConfigV2 instance. Implement a manual conversion from ConfigV1 to ConfigV2 which you call in case the object was ConfigV1.

In case you are only adding fields, this should not be needed as the deserialization should just skip the fields missing in the xml and leave default values.

Alternatively, you could implement custom deserialization by implementing ISerializable and a constructor (I didn't try this, you would have to try it yourself):

Config(SerializationInfo info,StreamingContext context) {
    this.angle = info.GetString("angle");
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜