如何阻止 XmlSerializer 发出空标记?
我有一个像这样的对象,
public class UserObj
{
public string First {get; set;}
public string Last {get; set;}
public addr Address {get; set;}
}
public class addr
{
public street {get; set;}
public town {get; set;}
}
现在当我在它上面使用 XmlSerializer 并且街道和城镇是空的时,我在 XML 输出中得到这个,
<Address />
有没有办法不输出这个空标签?
谢谢
I have an object like this,
public class UserObj
{
public string First {get; set;}
public string Last {get; set;}
public addr Address {get; set;}
}
public class addr
{
public street {get; set;}
public town {get; set;}
}
Now when I use XmlSerializer on it and street and town are empty I get this in the XML output,
<Address />
Is there a way not to output this empty tag?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以实现一个
ShouldSerializeAddress
方法来决定是否应序列化 Address 属性:如果该方法存在于此签名,则序列化程序将在序列化该属性之前调用它。
或者,您可以实现具有相同作用的
AddressSpecified
属性:You can implement a
ShouldSerializeAddress
method to decide whether or not the Address property should be serialized :If the method exists with this signature, the serializer will call it before serializing the property.
Alternatively, you can implement an
AddressSpecified
property which has the same role :您可以实施
IXmlSerialized
< /a> 并自行实现序列化例程。这样,您就可以避免该元素。这里是一个例子: http://paltman.com/2006/jul /03/ixmlserialized-a-persistable-example/
You may implement
IXmlSerializable
and implement the serialization routine on your own. This way, you can avoid the element.An example here: http://paltman.com/2006/jul/03/ixmlserializable-a-persistable-example/
您可以通过向属性添加 DefaultValue 特性来消除空值。当属性的值与默认值匹配时,它不会被序列化。您将默认值设置为 null,以消除序列化。这是一个例子:
You can eliminate the empty value by adding a DefaultValue attribute to the property. When the value of the property matches the default value, it isn't serialized. You set the default value to null, to eliminate the serialization. Here's an example:
我认为为地址字段分配空值应该可行。
I think assigning null value to address field should work.