Blog

XmlSerializer in C#

Posted 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


post comment
     
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts