c# - 在 C# 中将数组序列化为单个 XML 元素

标签 c# xml

假设我有 C# 代码

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

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

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

最佳答案

您需要创建额外的属性来将数组序列化为单个元素

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(",");
            }
        }
    }
}

输出:

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

关于c# - 在 C# 中将数组序列化为单个 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63385587/

相关文章:

c# - 如何在 asp.net core 中获取 .resx 文件字符串

c# - .NET Framework 中的 lambda 和委托(delegate)有什么区别?

AndroidPlot - XYplot 未显示在 xml 中的图形布局上

xml - 使用 HXT unpickler 忽略 XML 属性

sql-server - 日期类型的 XML 后代的 MIN

android - 当回收器 View 项目根是 LinearLayout 时,为什么 match_parent 不起作用?

xml - 如何验证 HTTP 重定向绑定(bind)的 SAML 签名

c# - GetHashCode 相等

c# - 使用两个 View 并在 View 之间切换

c# - 结构中字符串的管理