作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用 ASP.NET MVC 和来自 MVCContrib 的 XmlResult。
我有一个 Xxxx 对象数组,我将其传递给 XmlResult。
这被序列化为:
<ArrayOfXxxx>
<Xxxx />
<Xxxx />
<ArrayOfXxxx>
我希望它看起来像这样:
<Xxxxs>
<Xxxx />
<Xxxx />
<Xxxxs>
有没有一种方法可以指定一个类作为数组的一部分时如何序列化?
我已经在使用 XmlType 来更改显示名称,是否有类似的东西可以让您在数组中设置其组名称。
[XmlType(TypeName="Xxxx")]
public class SomeClass
或者,我是否需要为此集合添加包装器类?
最佳答案
这可以通过两种方式实现(使用包装器并在其上定义 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 .
关于c# - 将对象数组序列化为 Xxxxs 而不是 ArrayOfXxxx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2729921/
我正在使用 ASP.NET MVC 和来自 MVCContrib 的 XmlResult。 我有一个 Xxxx 对象数组,我将其传递给 XmlResult。 这被序列化为: 我希望它看
我是一名优秀的程序员,十分优秀!