简体   繁体   English

如果 object 为空,我如何不序列化 object

[英]How do I not Serialize an object if the object is empty

Is there a way to not Serialize an object if the object value is null?如果 object 的值为 null,有没有办法不序列化 object? My xml keeps having a lot of empty我的 xml 一直有很多空

<PersonName></PersonName>

(There is no other object with this value that it's serializing.) (没有其他 object 具有正在序列化的此值。)

The System.Xml.Serialization.XmlSerializer by default skips null properties. System.Xml.Serialization.XmlSerializer默认跳过 null 属性。 So you don't have to do anything.所以你不必做任何事情。
Obviously, you need to skip properties equal to string.Empty .显然,您需要跳过等于string.Empty的属性。

When using XmlSerializer , you can apply the System.ComponentModel.DefaultValue attribute to specify a value that will not be serialized.使用XmlSerializer时,您可以应用System.ComponentModel.DefaultValue属性来指定一个不会被序列化的值。

For example, you have next class:例如,您有下一个 class:

public class Person
{        
    public int Id { get; set; }

    [DefaultValue("")]
    public string PersonName { get; set; }

    public int Age { get; set; }
}

When using the following code使用以下代码时

var person = new Person { Id = 1, PersonName = "", Age = 20 };

var ser = new XmlSerializer(typeof(Person));
var settings = new XmlWriterSettings { Indent = true };
using (var writer = XmlWriter.Create("result.xml", settings))
{
    ser.Serialize(writer, person);
}

You will get this result你会得到这个结果

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>1</Id>
  <Age>20</Age>
</Person>

But be careful: this attribute is not taken into account during deserialization.但要小心:在反序列化过程中不会考虑此属性。 Therefore, from such XML you will get a Person class with the PersonName property equal to null .因此,从这样的 XML 你将得到一个Person class ,其PersonName属性等于null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM