Blog

XmlSerializer in C#

By Manish Tewatia Blogs | XML May 04, 2011
XmlSerializer enables you to control how objects are encoded into XML.

The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors. If you use any of the constructors other than the one that takes a type then a new temporary assembly is created EVERY TIME you create a serializer, rather than only once. It allows you to serializeand deserialize objects into and from XML documents. It enables youto control how objects are encoded into XML. The class constructoraccepts the object type to serialize.

The list of XmlSerializer members are given below:

  • XmlSerializer
  • XmlSerializer(Type)
  • XmlSerializer(XmlTypeMapping)
  • XmlSerializer(Type, String)
  • XmlSerializer(Type, Type())
  • XmlSerializer(Type, XmlAttributeOverrides)
  • XmlSerializer(Type, XmlRootAttribute)
  • XmlSerializer(Type, XmlAttributeOverrides, Type(), XmlRootAttribute, String)
  • XmlSerializer(Type, XmlAttributeOverrides, Type(), XmlRootAttribute, String, String)
  • XmlSerializer(Type, XmlAttributeOverrides, Type(), XmlRootAttribute, String, String, Evidence)

Example

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
 
public class Main
{
 
    public static void Main()
    {
        XmlSerializer serialization = new XmlSerializer(typeof(Product));
        Product car = new Product("BMW", 1, 10000000);
 
        serialization.Serialize(Console.Out, car);
        Console.ReadLine();
 
    }
}
 
public class Product
{
 
    [XmlElementAttribute("Name")]
    public string name;
    [XmlAttributeAttribute("Quantity")]
    public int quantity;
    [XmlAttributeAttribute("Price")]
    public int price;
 
    public Product()
    {
    }
 
    public Product(string name, int quantity, int price)
    {
        this.name = name;
        this.quantity = quantity;
        this.price = price;
    }
}

Output

xml2.gif


COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs