這是可能的兩種方式(使用包裝和定義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的源代碼並實現了你的答案。效果很好,謝謝你的幫助! – 2010-04-29 11:22:49