我正在使用XmlSerializer。它将对象序列化很好,但客户端要求所需的空元素采用此格式<star:Confirm/>
。序列化器将空元素序列化为<star:Confirm></star:Confirm>
有没有办法将其更改为序列化客户端所需的方式。
答案 0 :(得分:7)
在尝试不同的事情之后,我偶然发现了解决方案。我将XmlElementAttribute.IsNullable
设置为true,就像之前的回答一样。
[System.Xml.Serialization.XmlElementAttribute(ElementName = "Confirm", IsNullable=true)]
public ConfirmType Confirm
{
get
{
return this.confirmField;
}
set
{
this.confirmField = value;
this.RaisePropertyChanged("Confirm");
}
}
然后在代码中设置确认类型时,我使用了默认构造函数,而不是将Confirm设置为null。
retval.ConfirmBODDataArea.Confirm = new ConfirmType();
此序列化为<star:Confirm/>
答案 1 :(得分:3)
您可以尝试将XmlElementAttribute.IsNullable
属性设置为true
。但是,请记住xsi:nil="true"
属性将作为结果输出。