将数组序列化为 C# 中的单个 XML 元素

Dav*_*xon 3 c# xml

假设我有 C# 代码

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

var foo = new Foo
{
    bar = new[] { "1", "2", "3" }
};
Run Code Online (Sandbox Code Playgroud)

我如何序列Foo.bar化为<bar>1,2,3</bar>

Dmi*_*hev 6

您需要创建附加属性以将数组序列化为单个元素

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(",");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <bar>1,2,3</bar>
</Foo>
Run Code Online (Sandbox Code Playgroud)