TransWikia.com

Serialise array as single XML element in C#

Stack Overflow Asked by David Poxon on January 25, 2021

Say I have the C# code

class Foo
{
    [XmlElement("bar")]
    public string[] bar;
}

var foo = new Foo
{
    bar = new[] { "1", "2", "3" }
};

How do I serialise Foo.bar as <bar>1,2,3</bar>?

One Answer

You need create additional property to serialize array as single element

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo
        {
            bar = new[] { "1", "2", "3" }
        };
        XmlSerializer serializer = new XmlSerializer(typeof(Foo));
        serializer.Serialize(Console.Out, foo);
    }
}

public class Foo
{
    [XmlIgnore]
    public string[] bar;

    [XmlElement("bar")]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string BarValue
    {
        get
        {
            if(bar == null)
            {
                return null;
            }
            return string.Join(",", bar);
        }
        set
        {
            if(string.IsNullOrEmpty(value))
            {
                bar = Array.Empty<string>();
            }
            else
            {
                bar = value.Split(",");
            }
        }
    }
}

output:

<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <bar>1,2,3</bar>
</Foo>

Correct answer by Dmitry Kolchev on January 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP