views:

254

answers:

1

I'm using ASP.NET MVC with XmlResult from MVCContrib.

I have an array of Xxxx objects, which I pass into XmlResult.

This gets serialized as:

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

I would like this to look like:

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

Is there a way to specify how a class gets serialized when it is part of array?

I'm already using XmlType to change the display name, is there something similar that lets you set its group name when in an array.

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

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

+1  A: 

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

I implemented this in second way:

here is an array of ints, I'm using 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();
}

the data variable (which holds 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"&gt;
  <int>1</int>
  <int>5</int>
  <int>7</int>
  <int>9</int>
  <int>13</int>
</ints>

So, insted of ArrayOfInt we got ints as a root name.

More about XmlSerializer's constructor I used could be found here.

Alex
At first I wasn't able to directly access the XmlSerializer's constructor as I'm using MvcContrib's XmlResult and it's hidden in there. So, I took the source code for XmlResult and implemented your answer. Works well, thanks for your help!
Richard