XML deserialization generic method

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 06:17:36

You can deserialize a generic List<T> just fine with XmlSerializer. However, first you need to add the XmlType attribute to your DocBalanceItem so it knows how the list elements are named.

[XmlType("Document")]
public class DocBalanceItem
{
    [XmlElement("Id")]
    public Guid DocId { get; set; }

    [XmlElement("Balance")]
    public decimal? BalanceAmount { get; set; }
}

Then modify your DeserializeDocBalances() method to return a List<T> and pass the serializer an XmlRootAttribute instance to instruct it to look for Root as the root element:

public List<T> DeserializeList<T>(string filePath)
{
    var itemList = new List<T>();

    if (File.Exists(filePath))
    {
        var serializer = new XmlSerializer(typeof(List<T>), new XmlRootAttribute("Root"));
        TextReader reader = new StreamReader(filePath);
        itemList = (List<T>)serializer.Deserialize(reader);
        reader.Close();
    }

    return itemList;
}

Then you should be able to do

var list = DeserializeList<DocBalanceItem>("somefile.xml");

Since the method now returns a generic List<T>, you no longer need to create custom collections for every type.

P.S. - I tested this solution locally with the provided document, it does work.

Any stringable object can be deserialized by following method.

public static T genericDeserializeSingleObjFromXML<T>(T value, string XmalfileStorageFullPath)
        {             
            T Tvalue = default(T);
            try
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(T));
                TextReader textReader = new StreamReader(XmalfileStorageFullPath);
                Tvalue = (T)deserializer.Deserialize(textReader);
                textReader.Close();

            }
            catch (Exception ex)
            {                   
            System.Windows.Forms.MessageBox.Show("serialization Error : " + ex.Message);                
            }
            return Tvalue;
        }

In order to use this method you should already serialize the object in xml file. Calling method is :

XmlSerialization.genericDeserializeSingleObjFromXML(new ObjectName(), "full path of the XML file");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!