3

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>
K.Z
  • 5,201
  • 25
  • 104
  • 240

2 Answers2

4

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 .

Ronak Patel
  • 630
  • 4
  • 15
1

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.

Sebi
  • 3,879
  • 2
  • 35
  • 62
  • so with current implementation and class constructor I don't need xml attributes? – K.Z Oct 19 '16 at 10:11
  • In final version of Gender class all I need Code and Description, the remaining attribute in my current Gender class is compliance with upcoming XML format – K.Z Oct 19 '16 at 10:13
  • @toxic you just need the [Serializeable] nothing more. With my second implementation. If you need special xml formats you have to go the handy way but if you just want to store your object and get it back you don't need these xml-attributes. – Sebi Oct 19 '16 at 10:13
  • yes all I need objects and don't need xml-attribute! do you have any example of that.? – K.Z Oct 19 '16 at 10:14
  • @toxic give me some minutes i will update my answer. It's nearly what i have written... – Sebi Oct 19 '16 at 10:17
  • @toxic I added example of what iam doing sometimes. – Sebi Oct 19 '16 at 10:34