gpt4 book ai didi

c# - 将对象数组序列化为 Xxxxs 而不是 ArrayOfXxxx

转载 作者:太空狗 更新时间:2023-10-30 01:27:30 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com