Search code examples
c#xmlxml-serializationxml-deserialization

C# Changing the element names of items in a list when serializing/deserializing XML


I have a class defined as below:

[XmlRoot("ClassName")]
public class ClassName_0
{
    //stuff...
}

I then create a list of ClassName_0 like such:

var myListInstance= new List<ClassName_0>();

This is the code I use to serialize:

var ser = new XmlSerializer(typeof(List<ClassName_0>));
ser.Serialize(aWriterStream, myListInstance);

This is the code I use to deserialize:

var ser = new XmlSerializer(typeof(List<ClassName_0>));
var wrapper = ser.Deserialize(new StringReader(xml));

If I serialize it to xml, the resulting xml looks like below:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfClassName_0 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ClassName_0>
        <stuff></stuff>
    </ClassName_0>
    <ClassName_0>
        <stuff></stuff>
    </ClassName_0>
</ArrayOfClassName_0>

Is there a way to serialize and be able to deserialize the below from/to a list of ClassName_0?

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfClassName xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ClassName>
        <stuff></stuff>
    </ClassName>
    <ClassName>
        <stuff></stuff>
    </ClassName>
</ArrayOfClassName>

Thanks!


Solution

  • Worked it out, finally, with the help of Jan Peter. XmlRoot was the wrong attribute to put on the class. It was supposed to be XmlType. With XmlType the desired effect is achieved.