简体   繁体   中英

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? My xml keeps having a lot of empty

<PersonName></PersonName>

(There is no other object with this value that it's serializing.)

The System.Xml.Serialization.XmlSerializer by default skips null properties. So you don't have to do anything.
Obviously, you need to skip properties equal to string.Empty .

When using XmlSerializer , you can apply the System.ComponentModel.DefaultValue attribute to specify a value that will not be serialized.

For example, you have next 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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