在使用标准的.NET XML序列化程序时,有没有办法隐藏所有空值?下面是我的类的输出示例.如果可以为空的整数设置为NULL,我不想输出它们.

当前Xml输出:

<?xml version="1.0" encoding="utf-8"?>
<myClass>
   <myNullableInt p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />
   <myOtherInt>-1</myOtherInt>
</myClass>

我想要的是:

<?xml version="1.0" encoding="utf-8"?>
<myClass>
   <myOtherInt>-1</myOtherInt>
</myClass>

推荐答案

您可以使用模式ShouldSerialize{PropertyName}创建一个函数,该模式告诉XmlSerializer是否应该序列化该成员.

例如,如果类属性名为MyNullableInt,则可以

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

这是完整的样品

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

用以下代码序列化

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

以下XML中的结果-请注意,没有年龄

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

.net相关问答推荐

从没有流的EventStore中读取流不存在异常

AutoMapper在实体框架查询后不知从哪里带来数据

ECS服务无法从Cognito获取配置

在 Rx 中,处理线程安全是否是消费者(IObserver)的责任?

使用 PowerShell 从文件夹中获取文件名的最快\最好的方法是什么?

即时窗口中的动态导致Microsoft.CSharp.RuntimeBinder.Binder未定义或导入错误

IIS Express - 500.19 无法读取配置文件 - 因为它正在查看错误的路径

如何防止和/或处理 StackOverflowException?

重新启动(回收)应用程序池

如何在 WPF 应用程序中使用 App.config 文件?

如何将自定义 UserControl 显示为对话框?

为什么 Interlocked.Exchange 不支持布尔类型?

C# 的浮点比较函数

风格上的差异:IDictionary vs Dictionary

DataGridView 在我的两个屏幕之一上的可怕重绘性能

为什么发布和调试模式下的代码行为不同?

如何使用 EPPlus 设置 XLSX 单元格宽度?

在 .Net 中调用 Web 服务时绕过无效的 SSL 证书错误

如何为我的 C# 应用程序创建产品密钥?

判断数据表中是否包含空值的最佳方法