2010-04-28 34 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

相關問題