Lou
Lou

Reputation: 4484

Upgrading the serializer for an XML file

I am making modifications to a legacy app which uses XmlSerializer to serialize/deserialize XML files into a class. The requirement is to change a certain property in the new app version, so that old files can be loaded like before, but an upgraded (more general) property should be persisted next time. The old property would then be ditched on next save.

To explain it a bit better, this is how the file looks:

<Data>
   <ImportantAnalysisResults>
        <ImportantAnalysisResult>...</ImportantAnalysisResult>
        <ImportantAnalysisResult>...</ImportantAnalysisResult>
        <ImportantAnalysisResult>...</ImportantAnalysisResult>
   </ImportantAnalysisResults>
</Data>

New app version should load the file properly, and replace the element name with the new one on next save:

<Data>
   <Results>
        <Result>...</Result>
        <Result>...</Result>
        <Result>...</Result>
   </Results>
</Data>

The <Data> element has many more properties, but this is one that needs to be changed. Also, ImportantAnalysisResult inherits from Result.

In my Data class, I tried doing something like this:

class Data 
{ 
    [Obsolete("Used for backward compatibility. Use Results instead.")]
    [XmlArrayItem("ImportantAnalysisResult", typeof(Result))]
    public List<Result> ImportantAnalysisResults
    {
        get { return _results; }
    }

    public List<Result> Results 
    {
        get { return _results; }
    }
}

But this would still save the old property back into the new file. What's the best way to make ImportantAnalysisResults disappear on next save?

Is there a way to simply "map" the old property to the new Results property while loading?

Upvotes: 4

Views: 96

Answers (1)

Cinchoo
Cinchoo

Reputation: 6332

One way of doing this is using XmlAttributeOverrides. It helps you to overrides xml serialization. Hope it helps.

XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();

//Add overrides to xmlAttributeOverrides, use sample from internet

XmlSerializer serializer = new XmlSerializer(typeof(Data), XmlAttributeOverrides);

Upvotes: 1

Related Questions