Gur*_*ion 117 .net c# xml-serialization
使用标准.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>
Run Code Online (Sandbox Code Playgroud)
我想要的是:
<?xml version="1.0" encoding="utf-8"?>
<myClass>
<myOtherInt>-1</myOtherInt>
</myClass>
Run Code Online (Sandbox Code Playgroud)
Chr*_*lor 239
您可以使用模式创建一个函数,该函数ShouldSerialize{PropertyName}告诉XmlSerializer它是否应该序列化成员.
例如,如果你的类属性被调用,MyNullableInt你可以拥有
public bool ShouldSerializeMyNullableInt()
{
return MyNullableInt.HasValue;
}
Run Code Online (Sandbox Code Playgroud)
这是一个完整的样本
public class Person
{
public string Name {get;set;}
public int? Age {get;set;}
public bool ShouldSerializeAge()
{
return Age.HasValue;
}
}
Run Code Online (Sandbox Code Playgroud)
使用以下代码进行序列化
Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);
Run Code Online (Sandbox Code Playgroud)
结果在以下XML中 - 注意没有Age
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Chris</Name>
</Person>
Run Code Online (Sandbox Code Playgroud)
Dan*_*ose 31
除了Chris Taylor写的内容之外:如果你有一些序列化的属性,你可以在你的类上有一个属性{PropertyName}Specified来控制它是否应该被序列化.在代码中:
public class MyClass
{
[XmlAttribute]
public int MyValue;
[XmlIgnore]
public bool MyValueSpecified;
}
Run Code Online (Sandbox Code Playgroud)
JPB*_*anc 25
它存在一个叫做的属性 XmlElementAttribute.IsNullable
如果IsNullable属性设置为true,则为已设置为空引用的类成员生成xsi:nil属性.
以下示例显示应用了该字段的字段XmlElementAttribute,并将IsNullable属性设置为false.
public class MyClass
{
[XmlElement(IsNullable = false)]
public string Group;
}
Run Code Online (Sandbox Code Playgroud)
您可以查看其他XmlElementAttribute更改序列化等名称.
小智 10
您可以定义一些默认值,它可以防止字段序列化.
[XmlElement, DefaultValue("")]
string data;
[XmlArray, DefaultValue(null)]
List<string> data;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87012 次 |
| 最近记录: |