在类级别声明 [XmlElement(IsNullable = true)]
有没有办法在类级别声明 [XmlElement(IsNullable = true)] 以便类中的所有属性都将被 XML 序列化,即使它们为 null?
例如
public BankAccount BankAccount { get;放; }
应该导致
,而不是默认的缺失元素。
我尝试了这个,但编译器(正确地)指出该属性对于类声明无效。
这样做的原因是我不想为所有属性指定这一点。
编辑:这是我正在使用的序列化方法:
var serializer = new XmlSerializer(FormType);
var stream = new MemoryStream();
serializer.Serialize(stream, form);
Is there a way to declare [XmlElement(IsNullable = true)] at class level so that all properties in the class will be XML serialized, even if they are null?
e.g.
public BankAccount BankAccount { get; set; }
Should result in <BankAccount xsi:nil="true" />
, rather than the default missing element.
I tried this but the compiler (correctly) states that the attribute is not valid for class declarations.
The reason for this is that I don't want to have to specify this for all properties.
Edit: This is the serialization method I am using:
var serializer = new XmlSerializer(FormType);
var stream = new MemoryStream();
serializer.Serialize(stream, form);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,在为 XML 序列化类注释时必须明确。
每个属性都必须使用其自己的 XmlElement 属性进行注释,除非您想要默认行为。
Unfortunately you have to be explicit when annotating your class for XML serialization.
Each property must be annotated with its own XmlElement attribute unless you want a default behaviour.
请参阅此线程: 设置 [XmlElement(IsNullable = true)] 属性运行时间
see this thread: Setting the [XmlElement(IsNullable = true)] attribute at run time
你可以这样做,注意这仅涵盖简单的嵌套类
You could do it like this, note this only covers simple nested classes