具有新枚举值的 XmlSerializer [英] XmlSerializer with new enum values

查看:25
本文介绍了具有新枚举值的 XmlSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在项目中广泛使用 xml 序列化/反序列化在多个应用程序之间传递数据.我们有一个通用的 xsd,我们从中生成 c# 类,然后使用 XmlSerializer 从 xml 到对象再返回.

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.

我们遇到的问题是当一个应用程序更新以添加新的枚举值但另一个应用程序尚未更新时.现在未更新的应用程序尝试反序列化 xml 并失败,因为它不知道新的枚举.

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.

如果我们有 app1 和 app2,那么在现场工作正常,那么 app2 会在 xsd 中更新一个新的枚举值,并在现场更新到客户端.突然 app1 中断,因为它不知道枚举,app1 甚至可能不会使用该枚举字段,对 app1 没有影响,但它仍然中断.

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.

XmlSerializer 和 DataContractSerializer 都抛出异常就是这种情况.

Both XmlSerializer and DataContractSerializer throw exceptions is this situation.

我查看了自定义 xml 序列化项目 YAXLib (http://www.codeproject.com/KB/XML/yaxlib.aspx) 这也会引发异常,但有源代码并且可以更改.该项目使用不同的属性属性,需要进行相当多的更改,但可能是可行的.

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.

任何其他建议.

推荐答案

不幸的是,没有办法控制如何反序列化枚举值...作为一种解决方法,您可以将枚举值序列化为字符串:

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
}

这篇关于具有新枚举值的 XmlSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆