0

This is my Model class:

 public class ModelClass
 {
    public ModelClass()
    {
    }

    public ModelClass(string operationName)
    {
        OperationName = operationName;
    }
    public string OperationName { get; set; }
    public int Count { get; set; }
 }

I have to serialize a list of this model class to a database table: The table schema is:

ModelObjectContent (the serialized string)
IDModel

The method wich I use to serialize:

  public static string SerializeObject(this List<ModelClass> toSerialize)
    {
        var xmlSerializer = new XmlSerializer(toSerialize.GetType());
        var textWriter = new StringWriter();

        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }

When I save it to the database the string generated is like this:

 <ArrayOfChartModel>
     <ModelClass>
         <OperationName>Chart1</OperationName>
         <Count >1</Count>
      </ModelClass>
      <ModelClass>
         <OperationName>Chart2</OperationName>
         <Count >2</Count>
    </ModelClass>
    //etc
 </ArrayOfChartModel>

The framework automattically creates a tag named ArrayOfChartModel and thats ok, but my question is:
How to deserealize this xml to a list of ModelClass again?

rene
  • 41,474
  • 78
  • 114
  • 152
gog
  • 11,788
  • 23
  • 67
  • 129
  • Look at this that I answered before. It might help: http://stackoverflow.com/questions/23369197/how-to-create-c-sharp-objects-using-xml/23372505#23372505 – merp May 12 '14 at 18:57
  • Oh and this is a duplicate: http://stackoverflow.com/questions/608110/is-it-possible-to-deserialize-xml-into-listt – merp May 12 '14 at 19:03
  • @OhaxNuv this question asks how to desearilize a list of an object, and the correct answer is about to serialize. I dont get it. – gog May 12 '14 at 19:05
  • The second comment I added is the exact answer to what you said `How to deserealize this xml to a list of ModelClass again?` – merp May 12 '14 at 19:08

1 Answers1

0

This should work for you:

    public static List<ModelClass> Deserialize(string xml)
    {
        var xmlSerializer = new XmlSerializer(typeof(ModelClass));
        using (TextReader reader = new StringReader(xml))
        {
            return(List<ModelClass>)xmlSerializer.Deserialize(reader);
        }
    }