Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an attribute to skip empty arrays in the xml-serialization of c#?

Is there an attribute to skip empty arrays in the xml-serialization of c#? This would increase human-readability of the xml-output.

like image 887
Matze Avatar asked Dec 19 '08 08:12

Matze


People also ask

What is serialization in XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is XML serialization and Deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.

Why do we use XML serializer class?

XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.


1 Answers

Well, you could perhaps add a ShouldSerializeFoo() method:

using System;
using System.ComponentModel;
using System.Xml.Serialization;
[Serializable]
public class MyEntity
{
    public string Key { get; set; }

    public string[] Items { get; set; }

    [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
    public bool ShouldSerializeItems()
    {
        return Items != null && Items.Length > 0;
    }
}

static class Program
{
    static void Main()
    {
        MyEntity obj = new MyEntity { Key = "abc", Items = new string[0] };
        XmlSerializer ser = new XmlSerializer(typeof(MyEntity));
        ser.Serialize(Console.Out, obj);
    }
}

The ShouldSerialize{name} patten is recognised, and the method is called to see whether to include the property in the serialization. There is also an alternative {name}Specified pattern that allows you to also detect things when deserializing (via the setter):

[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[XmlIgnore]
public bool ItemsSpecified
{
    get { return Items != null && Items.Length > 0; }
    set { } // could set the default array here if we want
}
like image 192
Marc Gravell Avatar answered Sep 29 '22 19:09

Marc Gravell