[英]Serialize an array of objects as Xxxxs rather than ArrayOfXxxx
我正在使用ASP.NET MVC和MVCContrib的XmlResult。
我有一個Xxxx對象數組,我將其傳遞給XmlResult。
這被序列化為:
<ArrayOfXxxx>
<Xxxx />
<Xxxx />
<ArrayOfXxxx>
我希望這看起來像:
<Xxxxs>
<Xxxx />
<Xxxx />
<Xxxxs>
有沒有辦法指定類在數組的一部分時如何序列化?
我已經在使用XmlType來更改顯示名稱了,有類似的東西可以讓你在數組中設置它的組名。
[XmlType(TypeName="Xxxx")]
public class SomeClass
或者,我是否需要為此集合添加包裝類?
這可以通過兩種方式實現(使用包裝器並在其上定義XmlRoot
屬性,或者將XmlAttributeOverrides
添加到序列化程序)。
我以第二種方式實現了這個:
這是一個int數組,我正在使用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
的構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.