可能重复: XML序列化和空值 - C# change XmlSerializer的是如何序列化空元素
如何使XmlSerializer的存储空标签具有字符串属性为空值,而不是跳过这个属性?
解决方案你的意思是你想这样的:
<父>
< child1>的Hello World< / child1>
<的child2 />
< /父>
而不是
<父>
< child1>的Hello World< / child1>
< /父>
你的类应该是这样的:
串行器调用 ShouldSerializePropertyName
方法,通过定义(如果存在的话),以确定是否一个属性应序列(如Windows窗体设计器,太)。
公共类父
{
[的XmlElement(Child1)]
公共字符串Child1 {获得;组; }
[的XmlElement(CHILD2)]
公共字符串CHILD2 {获得;组; }
公共BOOL ShouldSerializeChild2(){返回true; }
}
Possible Duplicate: XML Serialization and null value - C# change how XmlSerializer serializes empty elements
How to make XmlSerializer store empty tags for string properties having null values, instead of skipping this property?
解决方案You mean you want this:
<parent>
<child1>Hello World</child1>
<child2 />
</parent>
instead of
<parent>
<child1>Hello World</child1>
</parent>
your class should look like this:
The serializer calls a ShouldSerializePropertyName
method by definition (if exists) to determine if a property should be serialized (like Windows Forms Designer, too).
public class Parent
{
[XmlElement("Child1")]
public string Child1 { get; set; }
[XmlElement("Child2")]
public string Child2 { get; set; }
public bool ShouldSerializeChild2() { return true; }
}