【问题标题】:Serialize an array of objects as Xxxxs rather than ArrayOfXxxx将对象数组序列化为 Xxxxs 而不是 ArrayOfXxxx
【发布时间】:2010-04-28 13:41:22
【问题描述】:

我正在使用带有来自 MVCContrib 的 XmlResult 的 ASP.NET MVC。

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

这被序列化为:

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

我希望它看起来像:

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

当一个类是数组的一部分时,有没有办法指定它如何被序列化?

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

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

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

【问题讨论】:

    标签: c# asp.net-mvc xml-serialization


    【解决方案1】:

    这可以通过两种方式实现(使用包装器并在其上定义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 的源代码并实现了您的答案。效果很好,感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    相关资源
    最近更新 更多