VARAK
VARAK

Reputation: 845

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!

Upvotes: 5

Views: 1840

Answers (4)

quangho
quangho

Reputation: 61

You make a root of document tree and this root will contain list of any object.

[XmlRootAttribute("myDocument")]
public class myDocument
{
   [XmlArrayAttribute]
   publict ClassName[] ArrayOfClassName {get;set;}
}

[XmlType(TypeName="ClassName")]
public class ClassName 
{
   public string stuff {get;set;}
}

Upvotes: 0

AKD
AKD

Reputation: 3966

try this :

XmlType(TypeName="ClassName")]
public class ClassName_0
{
    //stuff...
}

Upvotes: 1

VARAK
VARAK

Reputation: 845

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.

Upvotes: 0

Jan Peter
Jan Peter

Reputation: 920

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.

Upvotes: 2

Related Questions