当我使用标准的.NET Xml Serializer时,有什么办法可以隐藏所有的空值吗?以下是我的类的输出示例。如果设置为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>
发布于 2018-03-07 11:54:08
你可以使用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的结果 - 注意没有Age
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Chris</Name>
</Person>
发布于 2018-03-07 13:17:15
如果你有序列化为属性的东西,你可以在你的类上有一个属性{PropertyName}Specified
来控制它是否应该被序列化。在代码中:
public class MyClass
{
[XmlAttribute]
public int MyValue;
[XmlIgnore]
public bool MyValueSpecified;
}
https://stackoverflow.com/questions/-100003586
复制相似问题