Home > Software design >  How do I not Serialize an object if the object is empty
How do I not Serialize an object if the object is empty

Time:09-30

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.)

CodePudding user response:

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.

CodePudding user response:

Could you try

if(obJectToSerialize != null)
{
    // Serialize
}
  • Related