使用 XmlSerializer 时如何排除空属性 [英] How to exclude null properties when using XmlSerializer

查看:44
本文介绍了使用 XmlSerializer 时如何排除空属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在序列化这样的类

public MyClass
{
    public int? a { get; set; }
    public int? b { get; set; }
    public int? c { get; set; }
}

所有类型都是可为空的,因为我希望在序列化这种类型的对象时存储最少的数据.但是,当它仅填充a"进行序列化时,我得到以下 xml

All of the types are nullable because I want minimal data stored when serializing an object of this type. However, when it is serialized with only "a" populated, I get the following xml

<MyClass ...>
    <a>3</a>
    <b xsi:nil="true" />
    <c xsi:nil="true" />
</MyClass>

如何将其设置为仅获取非空属性的 xml?所需的输出是

How do I set this up to only get xml for the non null properties? The desired output would be

<MyClass ...>
    <a>3</a>
</MyClass>

我想排除这些空值,因为会有几个属性,并且这些属性被存储在数据库中(是的,那不是我的调用),所以我想尽量减少未使用的数据.

I want to exclude these null values because there will be several properties and this is getting stored in a database (yeah, thats not my call) so I want to keep the unused data minimal.

推荐答案

我想你可以创建一个 XmlWriter 来过滤掉所有具有 xsi:nil 属性的元素,并将所有其他调用传递给底层真正的 writer.

I suppose you could create an XmlWriter that filters out all elements with an xsi:nil attribute, and passes all other calls to the underlying true writer.

这篇关于使用 XmlSerializer 时如何排除空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆