反序列化枚举
我有一个 xml,其中一个元素的属性可以为空。 例如,
<tests>
<test language="">
.....
</test>
</tests>
现在,语言是从模式创建的类中的枚举类型。如果指定了语言,它就可以正常工作,如果它为空,则无法反序列化(如示例所示)。
编辑:反序列化代码:
XmlSerializer xmlserializer = new XmlSerializer(type);
StringReader strreader = new StringReader(stringXML);
Object o = serializer.Deserialize(strreader);
我该如何处理这种情况
I have an xml in which one of the elements has an attribute that can be blank.
For e.g.,
<tests>
<test language="">
.....
</test>
</tests>
Now, language is enum type in the classes created from the schema. It works fine if the language is specified, it fails to deserialize if it is blank (as shown in example).
Edit: Code for deserialization:
XmlSerializer xmlserializer = new XmlSerializer(type);
StringReader strreader = new StringReader(stringXML);
Object o = serializer.Deserialize(strreader);
How can I handle this scenario
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
<罢工>
您可以将枚举属性声明为可为空:
编辑:好的,我刚刚尝试过,它不适用于属性...这是另一个选项:不要序列化/反序列化此属性直接,但序列化一个字符串属性:
You could declare the enum property as nullable:
EDIT: ok, I just tried, it doesn't work for attributes... Here's another option: don't serialize/deserialize this property directly, but serialize a string property instead :
你可以这样做:
You can do it this way:
您可能需要标记枚举,并添加代表 Unknown 的默认项。
例如:
有关详细信息,请参阅此处 。
You probably need to mark up your enumeration, and add a default item that represents Unknown.
For example:
For more information, see here.
您希望结果是什么?
空白值无法映射到 null 引用,因为枚举是不可为 null 的值类型。
What would you want the result to be ?
A blank value cannot be mapped to a null reference since an enum is a non-nullable value type.
这是我想尝试的。它被称为空合并运算符,当我想要空输入的默认值时我使用它。
Is what I'd try. It's called Null-Coalescing operator, I use it when I want a default for null input.