在反序列化期间使用XML装饰指定默认值 [英] Using XML decorations to specify default values during de-serialization
问题描述
我在反序列化某些XML时遇到问题;第三方提供的XML非常冗长,因此,如果没有为特定元素设置任何值,它将提供空白元素(例如< element1 />
)。
I have a problem deserializing some XML; the XML supplied by a third party is quite verbose, so if there is no value set for an particular element, it will supply and empty element (e.g. <element1 />
).
这对于某些元素(例如,用于存储整数的元素)是一个问题。我可以控制第三方,因此我可以让他们指定默认值(< myinteger> 0< / myinteger>
),也可以忽略它们这些元素完全。两者都应避免出现问题。
This is a problem for certain elements, for example, those that are meant to store integers. I have control over the third party, so I could either get them to specify a default value (<myinteger>0</myinteger>
) or I can get them to omit these elements entirely. Both of these should avoid the problem.
但是,将来可能会出现一些情况,我们没有太多的控制权-在这种情况下,有没有办法
However, there may be situations in future, where we don't have so much control - in which case, is there a way of specifying, perhaps via a decoration, a default value?
[XmlElement("myinteger")=0???]
public int MyInteger
{
get
{
return myInteger;
}
set
{
myInteger= value;
}
}
推荐答案
XmlSerializer
确实支持 [DefaultValue]
,但它在序列化期间使用强>。在反序列化期间,它仅运行构造函数,然后获取传入的值并应用它们。因此,一种常见的方法是使用构造函数(或字段初始化器):
XmlSerializer
does support [DefaultValue]
, but it uses it during serialization. During deserialization, it simply runs the constructor, then takes incoming values and applies them. A common approach, then, is to use the constructor (or field-initializers):
public Foo() {
Bar = 4;
}
[DefaultValue(4), XmlAttribute("bar")]
public int Bar {get;set;}
但是; XmlSerializer
对此的解释不是提供一个空元素,而是忽略该元素(/属性)。甚至 int?
也不会映射为空。要处理 empty 元素,您必须将其作为字符串处理。这很丑。
However; XmlSerializer
's interpretation of this is not "supply an empty element" - but rather "omit the element(/attribute)". Even int?
doesn't map to "empty". To handle empty elements, you would have to handle it as a string. Which is ugly.
这篇关于在反序列化期间使用XML装饰指定默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!