Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 363
K.Z Avatar asked May 16 '26 03:05

K.Z


2 Answers

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 .

like image 120
Ronak Patel Avatar answered May 18 '26 17:05

Ronak Patel


If you want to serialize and deserialize an object with xml this is the easiest way:

The class we want to serialize and deserialize:

[Serializable]
public class Person()
{
   public int Id {get;set;}
   public string Name {get;set;}
   public DateTime Birth {get;set;}
}

Save an object to xml:

public static void SaveObjectToXml<T>(T obj, string file) where T : class, new()
{
   if (string.IsNullOrWhiteSpace(file))
      throw new ArgumentNullException("File is empty");

   var serializer = new XmlSerializer(typeof(T));
   using (Stream fileStream = new FileStream(file, FileMode.Create))
   {
      using (XmlWriter xmlWriter = new XmlTextWriter(file, Encoding.UTF8))
      {
        serializer.Serialize(xmlWriter, obj);
      }
   }
}

Load an object from xml:

public static T LoadObjectFromXml<T>(string file) where T : class, new()
{
    if (string.IsNullOrWhiteSpace(file))
      throw new ArgumentNullException("File is empty");

    if (File.Exists(file))
    {
      XmlSerializer deserializer = new XmlSerializer(typeof(T));
      using (TextReader reader = new StreamReader(file))
      {
         obj = deserializer.Deserialize(reader) as T;
      }
    }
}

How to use this methods with our Person class:

Person testPerson = new Person {Id = 1, Name="TestPerson", Birth = DateTime.Now};

SaveObjectToXml(testPerson, string "C:\\MyFolder");

//Do some other stuff

//Oh now we need to load the object
var myPerson = LoadObjectFromXml<Person>("C:\\MyFolder");

Console.WriteLine(myPerson.Name); //TestPerson

The Save and Load Methods are working with every object which class is [Serializable] and which contains public empty constructor.

like image 22
Sebi Avatar answered May 18 '26 18:05

Sebi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!