简体   繁体   English

XML序列化和空值 - C#

[英]XML Serialization and null value - C#

I have an object that I serialize to XML. 我有一个对象,我序列化为XML。 If one of the properties in the object is null, then native serialization ignores to add this as the attribute. 如果对象中的某个属性为null,则本机序列化将忽略将其添加为属性。 Is this normal behavior, if so, is there a way I can override it? 这是正常行为,如果是这样,有没有办法可以覆盖它?

ex: 例如:

public class Test
{
  [XmlAttribute]
  public string value {set; get; }

  [XmlAttribute]
  public string key {set; get; }
}

When value is null, i get 当值为null时,我得到

<Root>
  <Test key="blah">
</Root>

如果Sunny的答案不适合您,您可以通过实现IXmlSerializable接口来自定义序列化过程

For some background, take a look at the following ibm article Representations of null in XML Schema 对于某些背景知识,请查看以下ibm文章XML Schema中的null表示

Additionally check out the answer SO question Serialize a nullable int may be helpful in your efforts. 另外,请查看答案。问题序列化一个可空的int可能对您的工作有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM