Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XML Serialization of an array - Skip "empty" string values

I want to skip the empty element creation in XML file during the xml Serialization in C#.

Ex :

ArrayElements elm = new ArrayElements 
{ Items =new string[]  "Item1", " ", "Item2", " ", " ", "Items" } };

During the serialization it should skip the empty strings.

This is my class :

[Serializable]
public class ArrayElements
{
    [XmlElement(IsNullable=false)]
    public string[] Items { get; set; }
}
like image 790
user146584 Avatar asked Aug 18 '09 03:08

user146584


2 Answers

You can do it with a surrogate property.

namespace Cheeso.Xml.Samples.Arrays
{
    static class Extensions
    {
        private static XmlSerializerNamespaces _ns;

        static Extensions()
        {
            // to suppress unused default namespace entries in the root elt
            _ns = new XmlSerializerNamespaces();
            _ns.Add( "", "" );
        }

        public static string SerializeToString(this XmlSerializer s, object o)
        {
            var builder = new System.Text.StringBuilder();
            var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent= true };

            using ( var writer = System.Xml.XmlWriter.Create(builder, settings))
            {
                s.Serialize(writer, o, _ns);
            }
            return builder.ToString();
        }
    }

    [XmlType("ArrayOfString")]
    public class MyContainer
    {
        [XmlIgnore]
        public String[] a;

        // surrogate property
        [XmlElement("string")]
        public String[] A
        {
            get
            {
                List<String> _proxy = new List<String>();
                foreach (var s in a)
                {
                    if (!String.IsNullOrEmpty(s))
                        _proxy.Add(s);
                }
                return _proxy.ToArray();
            }
            set
            {
                a = value;
            }
        }
    }

    class StringArrayOnlyNonEmptyItems
    {
        static void Main(string[] args)
        {
            try 
            {
                Console.WriteLine("\nRegular Serialization of an array of strings with some empty elements:");
                String[] x = { "AAA", "BBB",  "",  "DDD",  "", "FFF" };
                XmlSerializer s1 = new XmlSerializer(typeof(String[]));
                string s = s1.SerializeToString(x);
                Console.WriteLine(s);

                Console.WriteLine("\nSerialization of an array of strings with some empty elements, via a Container:");
                MyContainer c = new MyContainer();
                c.a = x;
                XmlSerializer s2 = new XmlSerializer(typeof(MyContainer));
                s = s2.SerializeToString(c);
                Console.WriteLine(s);
            }
            catch (System.Exception exc1)
            {
                Console.WriteLine("uncaught exception:\n{0}", exc1);
            }
        }
    }
}
like image 153
Cheeso Avatar answered Oct 19 '22 15:10

Cheeso


Are you sure this is what you want? One drawback, is that when you deserialize, you will not be able to get back the empty strings, since there's no way for the deserializer to know about them. Usually when you deserialize, you want to get back an instance that looks exactly like the one you originally serialized.

If that is what you want, then you have to tweak your object to suit the serialization process. As Cheeso suggests, a surrogate property is a good solution for this.

Also, just for clarity, am I correct to say you have an object ArrayElements that has a property Items, which is an array of strings?

like image 2
Nader Shirazie Avatar answered Oct 19 '22 17:10

Nader Shirazie