Serialize an array of objects as Xxxx, not ArrayOfXxxx

I am using ASP.NET MVC with XmlResult from MVCContrib.

I have an array of Xxxx objects that I pass to XmlResult.

It serializes as:

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

I would like it to look like this:

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

Is there a way to indicate how a class is serialized when it is part of an array?

I already use XmlType to change the display name, is there something similar that allows you to set its group name in the array.

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

Or do I need to add a wrapper class for this collection?

+4
source share
1 answer

This is possible in both directions (using the wrapper and defining the XmlRoot attribute on it or adding XmlAttributeOverrides to the serializer).

I implemented this in a second way:

here is an array from ints, I use XmlSerializer to serialize it:

 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(); } 

data variable (which contains a serialized array):

 <?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> 

So, insted from ArrayOfInt we got ints as the root name.

More about the XmlSerializer constructor that I used can be found here .

+4
source

Source: https://habr.com/ru/post/1308243/


All Articles