繁体   English   中英

将对象数组序列化为Xxxx而不是ArrayOfXxxx

[英]Serialize an array of objects as Xxxxs rather than ArrayOfXxxx

我正在使用ASP.NET MVC和MVCContrib的XmlResult。

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

这被序列化为:

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

我希望这看起来像:

<Xxxxs>
  <Xxxx />
  <Xxxx />
<Xxxxs>

有没有办法指定类在数组的一部分时如何序列化?

我已经在使用XmlType来更改显示名称了,有类似的东西可以让你在数组中设置它的组名。

[XmlType(TypeName="Xxxx")]
public class SomeClass

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

这可以通过两种方式实现(使用包装器并在其上定义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();
}

数据变量(包含序列化数组):

<?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的构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM