假设我有以下 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>
string.Join
将三个字符串合并,然后将bar
元素变为string
而不是string[]
。 - Flydog57