views:

1066

answers:

4

I want to serialize a collection of objects for storage/retrieval from my app.config file. (I'm using the code from an example from Jeff Attwood's blog entry The Last Configuration Section Handler.. Revisited).

What I want to know, is why collections of objects of type

public class MyClass
{
  ...
}

get serialized to an xml element called

<ArrayOfMyClass>...</ArrayOfMyClass>

In this example I'm using a generic list of MyClass objects. I've also tried creating a new class which inherits from List and the resultant xml is exactly the same.

Is there a way to override the xml element name used when serializing/deserializing?

+3  A: 

They don't if they are child elements of a type - you can use [XmlRoot], [XmlType], [XmlElement] and [XmlArray] and [XmlArrayItem] in various combinations to get different results - unfortunately, the specifics are dependent on the exact layout...

Marc Gravell
+3  A: 

Take a look at the XmlArrayAttribute attribute

Rowland Shaw
+4  A: 

When you inherit from List you can try something along the lines of

[Serializable]
[System.Xml.Serialization.XmlRoot("SuperDuperCollection")]
public class SuperDuperCollection : List<MyClass> { ... }

to decorate your class, using the different XmlAttributes should let you have control over the way the XML is output when serialized.

Just an additional edit with some Test Code and output:

[Serializable]
public class MyClass
{
public int SomeIdentifier { get; set; }
public string SomeData { get; set; }
}

....

SuperDuperCollection coll = new SuperDuperCollection
{
    new MyClass{ SomeData = "Hello", SomeIdentifier = 1},
    new MyClass{ SomeData = "World", SomeIdentifier = 2}
};

Console.WriteLine(XmlSerializeToString(coll));

Output:

<SuperDuperCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <MyClass>
    <SomeIdentifier>1</SomeIdentifier>
    <SomeData>Hello</SomeData>
  </MyClass>
  <MyClass>
    <SomeIdentifier>2</SomeIdentifier>
    <SomeData>World</SomeData>
  </MyClass>
</SuperDuperCollection>
Quintin Robinson
You can do without the additional class, check my updated answer
eglasius
A: 

I've got a similar situation here but the XmlSerializer gets 'confused' I think.

[Serializable][System.Xml.Serialization.XmlRoot("SuperDuperCollection")]public class SuperDuperCollection : List { public string someText {get;set;}

}

MyClass and the SuperDuperCollection is serialized, but someText never get's it to the finish for some reason.

Egbert