Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

c# - XmlSerializer: How to Deserialize an enum value that no longer exists

I am using the XMLSerializer to save this class to a file. The class has a string and an enum as shown below:

public class IOPoint
{
     string Name {get; set;}
     TypeEnum {get; set;}
}


public enum TypeEnum
{
    Temperature,
    Pressure,
    Humidity,
}

When serialized it looks like this.

<IOPoint>
  <Name>Relative Humidity</Name>
  <TypeEnum>Humidity</TypeEnum>
</IOPoint>

I've been serializing and deserializing this object with no problems for several versions. I no longer want to support Humidity, so I removed it from the enum. However, this causes an exception when deserializing from XML because the value in the TypeEnum field, Humidity, is not a valid value for the TypeEnum. This makes sense, but how to handle this?

What I'd like to do is just ignore this error. And leave the value as null. I've tried implementing the OnUnknownElement XmlDeserilizationEvent class. Unfortunately, this does not catch this error.

Any ideas on how to catch and ignore this error (I can clean up after the deserialization is complete).

Mitch

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can mark the member Obsolete

public enum TypeEnum
{
    Temperature,
    Pressure,
    [Obsolete]
    Humidity
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...