Wednesday 1 January 2014

Generate XML from the Class Template


In this post we are going to see how to generate the xml file from a template class. To generate the xml file from the class we have to specify the class as serialize and column as xml attribute to generate the values as attribute in xml file.


output:

<?xml version="1.0" encoding="utf-8"?>
<PeopleInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Peoples>
    <Person Name="Rajesh" Email="rajhseg@gmail.com" StreetAddress="R.E St" AdditionNotes="Notes 1" Birthday="2002-01-01T11:01:08.3657823+05:30" />
    <Person Name="Suresh" Email="sdsfs@gmail.com" StreetAddress="RG St" AdditionNotes="Notes 2" Birthday="1990-01-01T11:01:08.3667824+05:30" />
    <Person Name="Krish" Email="krisg@gmail.com" StreetAddress="GW St" AdditionNotes="Notes 3" Birthday="1992-01-01T11:01:08.3667824+05:30" />
  </Peoples>
</PeopleInfo>



C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    [Serializable]
    public class Person
    {
        [XmlAttribute]
        public string Name
        {
            get;
            set;
        }
         
        [XmlAttribute]
        public string Email
        {
            get;
            set;
        }

        [XmlAttribute]
        public string StreetAddress
        {
            get;
            set;
        }

        [XmlAttribute]
        public string AdditionNotes
        {
            get;
            set;
        }

        [XmlAttribute]
        public DateTime Birthday
        {
            get;
            set;
        }
    }

    [Serializable]
    public class PeopleInfo
    {       
        public List<Person> Peoples { set; get; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Person> Peoples = new List<Person>();
            Peoples.Add(new Person() {Name="Rajesh",Email="rajhseg@gmail.com",Birthday=DateTime.Now.AddYears(-12),AdditionNotes="Notes 1",StreetAddress="R.E St" });
            Peoples.Add(new Person() { Name = "Suresh", Email = "sdsfs@gmail.com", Birthday = DateTime.Now.AddYears(-24), AdditionNotes = "Notes 2", StreetAddress = "RG St" });
            Peoples.Add(new Person() { Name = "Krish", Email = "krisg@gmail.com", Birthday = DateTime.Now.AddYears(-22), AdditionNotes = "Notes 3", StreetAddress = "GW St" });

            PeopleInfo ert = new PeopleInfo() { Peoples = Peoples};
            XmlSerializer serialize = new XmlSerializer(typeof(PeopleInfo));
            TextWriter writer = new StreamWriter(@"D:\sample.xml", true);
            serialize.Serialize(writer, ert);
            Console.Read();
        }
    }
}


In this post you can learn how to generate xml file from a class template.

No comments:

Post a Comment