简体   繁体   中英

Serialise array as single XML element in C#

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> ?

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>

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