Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 745
VARAK Avatar asked Oct 22 '22 05:10

VARAK


1 Answers

In your example ClassName isn't the real root. The real root is your list. So you have to mark the list as the root element. Your class is just an XmlElement.

like image 65
Jan Peter Avatar answered Nov 12 '22 20:11

Jan Peter