سؤال

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?

هل كانت مفيدة؟

المحلول

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);
        }
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top