Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - XmlSerializer with new enum values

We use xml serialization / deserialization extensively in our project to pass data between multiple application. We have a common xsd that we generate c# classes from then use XmlSerializer to go from xml to objects and back.

The problem we are having is when one app is updated to add new enum values but the other app is not updated yet. Now the app that is not updated tries to deserialize the xml and fails because it doesn't know about the new enum.

If we have app1 and app2, things are working correctly in the field, then app2 is update with a new enum value in the xsd and updated to the client in the field. Suddenly app1 breaks because it doesn't know about the enum, app1 might not even use that enum field, has not effect on app1, but it still breaks.

Are there any known ways around this. Basically what i want to do is define what do do when an enum is not found, use a default value or if the enum as a nullible type and set it to null.

Both XmlSerializer and DataContractSerializer throw exceptions is this situation.

I've looked at the custom xml serialization project YAXLib (http://www.codeproject.com/KB/XML/yaxlib.aspx) this also throws an exception but there is source code and can be changed. This project use different property attributes and would require quite a bit of change but is probably doable.

Any other suggestions.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Unfortunately there's no way to control how enum values are deserialized... As a workaround, you could serialize the enum values as string :

[XmlIgnore]
public MyEnum MyProperty { get; set; }

[XmlElement("MyProperty")]
public string MyPropertyAsString
{
    get
    {
        return EnumToString(MyProperty);
    }
    set
    {
        MyProperty = StringToEnum<MyEnum>(value);
    }
}

public T StringToEnum<T>(string stringValue)
{
    // Manually convert the string to enum, ignoring unknown values
}

public string EnumToString<T>(T enumValue)
{
    // Convert the enum to a string
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...