Search code examples
c#xml-deserialization.net-4.5.2

Deserialize xml to Generic type


I need class which takes two parameter

1- Type ==> class name 2- xml string ==> xml document in string format.

now following class convert xml to object which is all working fine but I need final version as generic type

Converter class

public static partial class XMLPrasing
{
    public static Object ObjectToXML(string xml, Type objectType)
    {
        StringReader strReader = null;
        XmlSerializer serializer = null;
        XmlTextReader xmlReader = null;
        Object obj = null;
        try
        {
            strReader = new StringReader(xml);
            serializer = new XmlSerializer(objectType);
            xmlReader = new XmlTextReader(strReader);
            obj = serializer.Deserialize(xmlReader);
        }
        catch (Exception exp)
        {
            //Handle Exception Code
            var s = "d";
        }
        finally
        {
            if (xmlReader != null)
            {
                xmlReader.Close();
            }
            if (strReader != null)
            {
                strReader.Close();
            }
        }
        return obj;
    }

}

as Example class

[Serializable]
[XmlRoot("Genders")]
public class Gender
{

    [XmlElement("Genders")]
    public List<GenderListWrap> GenderListWrap = new List<GenderListWrap>();       
}


public class GenderListWrap
{
    [XmlAttribute("list")]
    public string ListTag { get; set; }

    [XmlElement("Item")]
    public List<Item> GenderList = new List<Item>();
}



public class Item
{
    [XmlElement("CODE")]
    public string Code { get; set; }

    [XmlElement("DESCRIPTION")]
    public string Description { get; set; }
}

//

<Genders><Genders list=\"1\">
<Item>
<CODE>M</CODE>
<DESCRIPTION>Male</DESCRIPTION></Item>
 <Item>
 <CODE>F</CODE>
 <DESCRIPTION>Female</DESCRIPTION>
 </Item></Genders>
 </Genders>

Solution

  • Please check my solution if it will help you.

    Below is Method, which converts xml to generic Class.

      public static T GetValue<T>(String value)
        {
            StringReader strReader = null;
    
            XmlSerializer serializer = null;
    
            XmlTextReader xmlReader = null;
    
            Object obj = null;
            try
            {
                strReader = new StringReader(value);
    
                serializer = new XmlSerializer(typeof(T));
    
                xmlReader = new XmlTextReader(strReader);
    
                obj = serializer.Deserialize(xmlReader);
            }
            catch (Exception exp)
            {
    
            }
            finally
            {
                if (xmlReader != null)
                {
                    xmlReader.Close();
                }
                if (strReader != null)
                {
                    strReader.Close();
                }
            }
            return (T)Convert.ChangeType(obj, typeof(T));
        }
    

    How to call that method :

    Req objreq = new Req();

    objreq = GetValue(strXmlData);

    Req is Generic Class . strXmlData is xml string .

    Request sample xml :

     <?xml version="1.0"?>
     <Req>
       <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications 
          with XML.</description>
       </book>
       <book id="bk102">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies, 
          an evil sorceress, and her own childhood to become queen 
          of the world.</description>
       </book>
      </Req>
    

    Request Class :

    [System.SerializableAttribute()]
    public partial class Req {
    
        [System.Xml.Serialization.XmlElementAttribute("book")]
        public catalogBook[] book { get; set; }
    
      }
    
    
    [System.SerializableAttribute()]
    public partial class catalogBook {
    
        public string author { get; set; }
    
        public string title { get; set; }
    
        public string genre { get; set; }
    
        public decimal price { get; set; }
    
        public System.DateTime publish_date { get; set; }
    
        public string description { get; set; }
    
        public string id { get; set; }
    
     }
    

    In my case it is working perfectly ,hope it will work in your example .

    Thanks .