5

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!

VARAK
  • 835
  • 10
  • 27
  • 1
    I think this link might be useful for you, http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document – sagar Jul 19 '13 at 08:11
  • Thanks for the link. Unfortunately, this is generated code, so I cannot create a custom list of the desired type and add all the element attributes to that. I can only add attributes to the classes themselves. – VARAK Jul 19 '13 at 08:12

4 Answers4

2

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.

Jan Peter
  • 912
  • 7
  • 19
1

try this :

XmlType(TypeName="ClassName")]
public class ClassName_0
{
    //stuff...
}
Ashok Damani
  • 3,896
  • 4
  • 30
  • 48
0

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.

VARAK
  • 835
  • 10
  • 27
0

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;}
}
quangho
  • 61
  • 1
  • 1
  • 6