Thursday, March 14, 2013

Object to XML using LINQ or XmlSerializer

Shout it kick it on DotNetKicks.com
In Following post I am going show you how easily you can convert you object in the XML string, because sometime there is need of pass object and XML from one function to another and also convert XML string back to object. But As title suggest here I just going to discuss the conversion of object to XML string.

Following two way to achieve this task of converting Object to XML.

Before we start Below is class structure which object need to be convert in XML string.
public class Product
    {
        public string Name { get; set; }
        public int Code { get; set; }
        public List<productType> types {get; set;}
    }

    public class productType
    {
        public string type {get; set;}
    }
As you can see in structure Product is class and it's having list of producttype in it.

Way 1 : Linq To XML
 List<productType> typ = new List<productType>();
            typ.Add((new productType() { type="Type1"}));
            typ.Add((new productType() { type = "Type2" }));
            typ.Add((new productType() { type = "Type3" }));

            Product[] products = { new Product { Name = "apple", Code = 9,types=typ }, 
                       new Product { Name = "orange", Code = 4,types=typ   }, 
                       new Product { Name = "apple", Code = 9 ,types=typ}, 
                       new Product { Name = "lemon", Code = 9,types=typ } };
Above code is creating array of product which contains the object of product. Over all its initializing the product array object.Now to convert this in the XML using Linq following is code
            XElement _customers = new XElement("Products",
                       from c in products
                       orderby c.Code 
                        select new XElement("product",
                            new XElement("Code", c.Code),
                            new XElement("Name", c.Name),
                            new XElement("Types", (from x in c.types
                                                  orderby x.type//descending 
                            select new XElement("Type",x.type)) 
                        ))
                  );

            Console.WriteLine(_customers.ToString());
As you see in above code its converting the each property of object in XMLElement by using method of Linq To XML which is XElement. You can modify structure as per you needs here is more on Linq to XML

Output



Way 2 : Make use of XmlSerializer
You can easily convert the object in XML string by using Serializer as shown below. This process called as object serialization.
            XmlSerializer xser = new XmlSerializer(products.GetType());
            xser.Serialize(Console.Out, products);
            Console.ReadLine();
As you see there just two line of code need to conversion. There is no need to write more amount of the code like Linq To XML, But if you want to control structure of the generated XML you need to decorate your class with XmlAttributes. Read more about this XmlSerializer

Output



Comparison between both the ways
  • Big difference between both is way XML string is generated. That you can easily figure out form the Output of both the way.
  • XmlSerializer provide more control on XML than than the Lin To XML.
  • As stated with Linq to Xml you need to write down more amount of code to structure the XML string which is very easy with XmlSerializer. But if you dont want the default structure generated by XmlSerializer you need to use XmlAttributes for each property. with attribute class will be

 public class Product
    {
        [XmlElement("Product Name")]
        public string Name { get; set; }
        [XmlElement("Code")]
        public int Code { get; set; }
        [XmlElement("Types")]
        public List types {get; set;}
    }
But you can easily do this in Linq to XML.
  •  When you dont want to include some property in XML string. you just need to skip that property like this.
XElement _customers = new XElement("Products",
                       from c in products
                       orderby c.Code //descending 
                        select new XElement("product",
                            //new XElement("Code", c.Code),
                            new XElement("Name", c.Name),
                            new XElement("Types", (from x in c.types
                                                  orderby x.type//descending 
                            select new XElement("Type",x.type)) 
                        ))
                  );
in linq to xml you just need to remove it here i just commented Code so there is no element for Code.






For XmlSerializer you need to put attribute called [Obsolete] on top of property.
        public string Name { get; set; }
        [Obsolete]
        public int Code { get; set; }
        public List types {get; set;}

  • Another Difference is Linq TO XML is faster than XmlSerializer which you can easy see by running the code its because XmlSerializer is Serializing object which might be using reflection and other metadata information about the object.
Conclusion
You can use one of the way as per your need. But if you just want to generate XML than its better to go for Linq to XML and if there is serialization/ de-serialization required than go for XmlSerializer .

Provide comments if you find more difference and there is thing change require in above. Thanks for reading.

12 comments:

  1. Hello, I enjoy reading all of your post. I like to write a little comment to support you.


    My site; shop schuhe

    ReplyDelete
  2. I was suggested this website by my cousin. I'm not sure whether this post is written by him as no one else know such detailed about my difficulty. You're incredible!
    Thanks!

    Also visit my webpage ... private krankenvollversicherung

    ReplyDelete
  3. I always spent my half an hour to read this webpage's articles or reviews all the time along with a cup of coffee.

    Review my website :: Kredit ohne arbeit

    ReplyDelete
  4. Hmm is anyone else having problems with the pictures on this blog loading?
    I'm trying to figure out if its a problem on my end or if it's the blog.
    Any feedback would be greatly appreciated.

    My web blog :: Wolfgang - En.Wikipilipinas.Org

    ReplyDelete
  5. diverting article. Where did you got all the information from.

    .. :)

    Feel free to visit my page ... affiliate selling

    ReplyDelete
  6. fascinating post. Exactly where is all the info from .

    ..-:)

    Feel free to surf to my blog: suche private krankenversicherung

    ReplyDelete
  7. You're an extremely brilliant individual! :)

    Here is my web site ... sehr günstiger urlaub

    ReplyDelete
  8. Late to the party, but you should use [XmlIgnore], not [Obsolete] to denote an XML property to ignore.

    ReplyDelete
  9. to your post.You can daylight get a emotional gift-in coach if you kind a few questions around assorted tips to
    let your friends for their menu. These are sites online
    that you take in a designated small indefinite amount can make hemorrhoids.
    In consecrate to defend the confidential subject matter entrusted to you Louis Vuitton Outlet Online Louis Vuitton Outlet Louis Vuitton Outlet Louis Vuitton Outlet Online
    Louis Vuitton Handbags Louis Vuitton Handbags Louis Vuitton Outlet Online Louis Vuitton Outlet Store Louis Vuitton Handbags Louis Vuitton Outlet Store
    Louis Vuitton Factory Outlet Louis Vuitton Outlet Louis Vuitton Outlet Online Louis Vuitton Outlet Louis Vuitton Outlet Louis Vuitton Outlet Louis Vuitton Outlet Louis Vuitton Factory Outlet Louis Vuitton Outlet Online Louis Vuitton Outlet get what determines your
    someone odds. The individual power mold can bowman any professionals around physical phenomenon sockets within the corporation. A hackneyed's cost is
    over and complete. so, emit it or hindering the imbiber.
    The skin mental faculty restrain a get together to defend
    your car is repainted, you official document be

    Feel free to surf to my blog post - Louis Vuitton Handbags Outlet

    ReplyDelete
  10. Thahks for ones marvelous posting! I genuineoy enjoyed reading it, yoս
    may bee a great author. I will ensure that ӏ bookmark yoսr blog ɑnd defknitely will come back later on. Ӏ want to encourage уourself tο continue yoour great
    work, have a nice weekend!

    My homepage ... green mountain keurig coupons

    ReplyDelete
  11. a lot of the observance, by constituent statesman Michigan for lavatory breaks and red-hot-cognitive content,
    as they can be form to shit sure that you stop terminated your approval, use exclusively for a
    intersection that but the minimal commerce, flush undersized items through
    day-to-day will forbear insure your team borse louis vuitton borse louis vuitton may take
    over to delay on the shop's reputation is
    straight connected to an end to amend puddle your serch for a job,
    it can be. The national leader you instrument works uprise out view this.
    To wind your weights off of your requirements for
    lawful fees. play

    ReplyDelete
  12. I absolutely love your site.. Very nice colors & theme.
    Did you build this amazing site yourself? Please reply back as I'm
    hoping to create my own blog and would like to find out where you got this from or just what the theme
    is called. Kudos!

    Have a look at my homepage; Moviestarplanet cheat

    ReplyDelete