这是可能的两种方式(使用包装和定义XmlRoot
属性,或添加XmlAttributeOverrides
串行器)。
我实现这在第二方式:
这里是整数数组,我使用的XmlSerializer
到序列化:
int[] array = { 1, 5, 7, 9, 13 };
using (StringWriter writer = new StringWriter())
{
XmlAttributes attributes = new XmlAttributes();
attributes.XmlRoot = new XmlRootAttribute("ints");
XmlAttributeOverrides attributeOverrides = new XmlAttributeOverrides();
attributeOverrides.Add(typeof(int[]), attributes);
XmlSerializer serializer = new XmlSerializer(
typeof(int[]),
attributeOverrides
);
serializer.Serialize(writer, array);
string data = writer.ToString();
}
数据变量(持有序列化阵列):
<?xml version="1.0" encoding="utf-16"?>
<ints xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<int>1</int>
<int>5</int>
<int>7</int>
<int>9</int>
<int>13</int>
</ints>
因此,我们得到ArrayOfInt
作为根名称ints
。
更多关于XmlSerializer
的构造函数我用过的可以找到here。
起初我无法直接访问XmlSerializer的构造函数,因为我使用的是MvcContrib的XmlResult,它隐藏在那里。所以,我拿了XmlResult的源代码并实现了你的答案。效果很好,谢谢你的帮助! – 2010-04-29 11:22:49