XML序列化 - 隐藏空值序列化、XML

2023-09-02 11:45:30 作者:自作多情死于非命

在使用标准的.NET Xml序列化,有没有什么办法可以隐藏所有空值?下面是我班的输出的一个例子。我不想输出可空整数,如果它们被设置为空。

当前XML输出​​:

< XML版本=1.0编码=UTF-8&GT?; < MyClass的>    < myNullableInt P2:零=真实的xmlns:P2 =htt​​p://www.w3.org/2001/XMLSchema-instance/>    &其中; myOtherInt>的-1 / myOtherInt> < / MyClass的>

我想:

< XML版本=1.0编码=UTF-8&GT?; < MyClass的>    &其中; myOtherInt>的-1 / myOtherInt> < / MyClass的> C 之xml序列化

解决方案

您可以用图案 ShouldSerialize {属性名} 它告诉XmlSerializer的,如果它应该序列创建一个函数该成员与否。

例如,如果你的类属性被称为 MyNullableInt 你可以有

 公共BOOL ShouldSerializeMyNullableInt()
{
  返回MyNullableInt.HasValue;
}
 

下面是一个完整的示例

 公共类Person
{
  公共字符串名称{获取;集;}
  公众诠释?年龄{获取;集;}
  公共BOOL ShouldSerializeAge()
  {
    返回Age.HasValue;
  }
}
 

连载具有以下code

 人员thePerson =新的Person(){名称=克里斯};
XmlSerializer的XS =新的XmlSerializer(typeof运算(人));
StringWriter的SW =新的StringWriter();
xs.Serialize(SW,thePerson);
 

在followng XML结果 - 请注意,没有年龄

 <人的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance
        的xmlns:XSD =htt​​p://www.w3.org/2001/XMLSchema>
  <名称>&克里斯LT; /名称>
< /人>
 

When using a standard .NET Xml Serializer, is there any way I can hide all null values? The below is an example of the output of my class. I don't want to output the nullable integers if they are set to null.

Current Xml output:

<?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>

What I want:

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

解决方案

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

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

Here is a full sample

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

Serialized with the following code

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

Results in the followng XML - Notice there is no Age

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