Serializer Update for XML File

I am making changes to an outdated application that uses the XmlSerializer to serialize / deserialize XML files into a class. The requirement is to change a specific property in the new version of the application so that the old files can be downloaded as before, but the updated (more general) property must be saved the next time. Then the old property will be reset the next time it is saved.

To explain this a little better, here is what the file looks like:

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

The new version of the application should load the file correctly and replace the element name with a new one the next time it is saved:

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

The <Data> element has many more properties, but this is the one that needs to be changed. In addition, ImportantAnalysisResult inherited from Result .

In my Data class, I tried to do 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 it still saves the previous property back to the new file. What is 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 on boot?

+4
source share
1 answer

One way to do this is with XmlAttributeOverrides . This will help you override XML serialization. Hope this helps.

 XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides(); //Add overrides to xmlAttributeOverrides, use sample from internet XmlSerializer serializer = new XmlSerializer(typeof(Data), XmlAttributeOverrides); 
+1
source

Source: https://habr.com/ru/post/1446027/


All Articles