简体   繁体   中英

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!

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.

try this :

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

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.

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;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM