使用可选标签反序列化 XML [英] Deserialize XML with optional tags
问题描述
我有一个带有可选标签的 XML,如下所示:
I have an XML with an optional tag as follows:
<Config>
<CheckForCompleteTransform>true</CheckForCompleteTransform>
<!-- more tags -->
</Config>
以及类定义:
public class config {
[System.Xml.Serialization.XmlElement("CheckForCompleteTransform")]
public bool? CheckForCompleteTransform { get; set; }
}
如果我将标签设置为我在上面的示例 XML 中提供的内容或者我完全省略它,这将起作用.但是,如果我将标签提供为 <MyTag/>
呢?如果使用此表示法,我希望序列化程序将我的类中的相应属性设置为 true,但我却得到一个
This works if I either set the tag to what I provided within my example-XML above or I omit it completely. But what if I provide the tag as <MyTag/>
? If this notation is used I want the serializer to set the corresponding property within my class to true, but I awlays get a
System.FormatException: 字符串文字 '' 对类型无效布尔值
System.FormatException: the string literal '' is not valid for type Boolean
关于如何实现这一目标的任何想法?
Any ideas on how to achieve this?
推荐答案
我自己还没有验证过,但是你有没有尝试添加一个
I haven't verified this myself, but have you tried adding a
[XmlElement(IsNullable = true)]
CheckForCompleteTransform 的属性?
attribute to the CheckForCompleteTransform ?
好吧,一起怎么样
DefaultValueAttribute(true);
这篇关于使用可选标签反序列化 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!