假设我有 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/