Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize collections in .net

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?

like image 747
Matthew Dresser Avatar asked Dec 31 '22 03:12

Matthew Dresser


1 Answers

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">
  <MyClass>
    <SomeIdentifier>1</SomeIdentifier>
    <SomeData>Hello</SomeData>
  </MyClass>
  <MyClass>
    <SomeIdentifier>2</SomeIdentifier>
    <SomeData>World</SomeData>
  </MyClass>
</SuperDuperCollection>
like image 199
Quintin Robinson Avatar answered Jan 13 '23 21:01

Quintin Robinson