Responsive Ads Here
Showing posts with label Generic Code For XML Generate in c#. Show all posts
Showing posts with label Generic Code For XML Generate in c#. Show all posts

Tuesday, September 26, 2017

XML Helper for convert class object/List to xml and xml to class object/List conversion


Hi friend's, today we are going to understand ubout XMl Helper for convert class object/List to xml and xml to class object/List convertion.

let's start with example,

Create class for EmployeeDetail


public class EmployeeDetails
    {
        [XmlAttribute]
        public int EmployeeID { get; set; }
        [XmlAttribute]
        public string EmployeeName { get; set; }
        [XmlAttribute]
        public string EmailID { get; set; }
        [XmlAttribute]
        public List lstEmployeeDetails { get; set; }
    }
Now, we have one class XMLHandler that contains two methods that make our work easy and clean.
  • Method ConvertToXML for Generic code to convert Xml to class object or list.
  • Method Convert for Generic code to convert class object or list to Xml.
public static class XMLHandler
    {
        public static T Convert(string inputString)
        {
              XmlSerializer serializer = new XmlSerializer(typeof(T), string.Empty);
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
              T resultingMessage = (T)(serializer.Deserialize(memStream));
              return resultingMessage;
        }
        public static string ConvertToXML(T obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringWriter sww = new StringWriter();
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                serializer.Serialize(writer, obj);
                return sww.ToString().Replace("", "").Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", ""); // Your XML
            }
        }
    }

To convert List to xml:
Now we will create instance for EmployeeDetails
EmployeeDetails objEmployeeDetails = new EmployeeDetails();
string xml = XMLHandler>.ConvertToXML(objEmployeeDetails. lstEmployeeDetails);
It will return xml as below Figure,



So, that's all guys i hope these will help you to create xml using object/class.
please share this blog if this helpful you. https://dotnetupdatedtechnology.blogspot.com/

{ "@context": "http://schema.org", "@type": "Organization", "url": "http://c-sharpnets.blogspot.com/", "logo": "http://c-sharpnets.blogspot.com/images/logo.png" }