C# 将对象数组序列化为Xxxxs而不是arrayOfxxx

C# 将对象数组序列化为Xxxxs而不是arrayOfxxx,c#,asp.net-mvc,xml-serialization,C#,Asp.net Mvc,Xml Serialization,我正在使用ASP.NETMVC和来自MVCContrib的XmlResult 我有一个Xxxx对象数组,我将其传递到XmlResult 这将被序列化为: <ArrayOfXxxx> <Xxxx /> <Xxxx /> <ArrayOfXxxx> 或者,我需要为此集合添加包装类吗?这两种方法都可以(使用包装并在其上定义XmlRoot属性,或者向序列化程序添加XmlAttributeOverrides) 我以第二种方式实现了这一点: 这是一个

我正在使用ASP.NETMVC和来自MVCContrib的XmlResult

我有一个Xxxx对象数组,我将其传递到XmlResult

这将被序列化为:

<ArrayOfXxxx>
  <Xxxx />
  <Xxxx />
<ArrayOfXxxx>

或者,我需要为此集合添加包装类吗?

这两种方法都可以(使用包装并在其上定义
XmlRoot
属性,或者向序列化程序添加
XmlAttributeOverrides

我以第二种方式实现了这一点:

这是一个int数组,我正在使用
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();
}
数据变量(包含序列化数组):


1.
5.
7.
9
13
因此,我们得到了
ints
作为根名称,而不是
ArrayOfInt


可以找到有关我使用的
XmlSerializer
构造函数的更多信息。

起初我无法直接访问XmlSerializer的构造函数,因为我使用的是MvcContrib的XmlResult,它隐藏在那里。因此,我获取了XmlResult的源代码并实现了您的答案。很好用,谢谢你的帮助!
[XmlType(TypeName="Xxxx")]
public class SomeClass
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>