XML 序列化和空值 - C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/711723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XML Serialization and null value - C#
提问by DotnetDude
I have an object that I serialize to XML. If one of the properties in the object is null, then native serialization ignores to add this as the attribute. Is this normal behavior, if so, is there a way I can override it?
我有一个序列化为 XML 的对象。如果对象中的属性之一为空,则本机序列化会忽略将其添加为属性。这是正常行为吗,如果是这样,有没有办法覆盖它?
ex:
前任:
public class Test
{
[XmlAttribute]
public string value {set; get; }
[XmlAttribute]
public string key {set; get; }
}
When value is null, i get
当值为空时,我得到
<Root>
<Test key="blah">
</Root>
采纳答案by Sunny Milenov
回答by Jhonny D. Cano -Leftware-
In case Sunny's answer just doesn't fits to you, you can customize the serialization process by implementing the IXmlSerializable interface
如果 Sunny 的回答不适合您,您可以通过实现 IXmlSerializable 接口来自定义序列化过程
回答by Robert Paulson
For some background, take a look at the following ibm article Representations of null in XML Schema
对于一些背景,请查看以下 ibm 文章Representations of null in XML Schema
Additionally check out the answer SO question Serialize a nullable intmay be helpful in your efforts.
此外,请查看答案 SO question Serialize a nullable int可能对您的工作有所帮助。