2010-04-28 33 views
4

我正在使用ASP.NET MVC和MVCContrib的XmlResult。将对象数组序列化为Xxxx而不是ArrayOfXxxx

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

这被序列为:

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

我想这个样子:

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

有没有规定如何,当它是阵列的一部分,一类被序列化的方法吗?

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

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

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

回答

4

这是可能的两种方式(使用包装和定义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

+0

起初我无法直接访问XmlSerializer的构造函数,因为我使用的是MvcContrib的XmlResult,它隐藏在那里。所以,我拿了XmlResult的源代码并实现了你的答案。效果很好,谢谢你的帮助! – 2010-04-29 11:22:49

相关问题