Writing Object to XML using XmlSerializer C# Source Code

How to write an object to a file with XML format? There is a class from .NET System.Xml.Serialization.XmlSerializer which can help to completely serialize the objects from program to a XML formatted files.

Suppose that we want to save the data of a person which has attributes:

  1. Name
  2. Age
  3. Height
  4. Weight

And the Person class:

public class Person
    public string name;
    public int age;
    public int height;
    public int weight;

    public Person() { }

    public Person(string name, int age, int h, int w)
        this.name   = name;
        this.age    = age;
        this.height = h;
        this.weight = w;

Then the writing serialized object method:

Person p = new Person("I Made Krisna", 22, 180, 65);

XmlSerializer serializer = new XmlSerializer(typeof(Person));
XmlWriter writer = new XmlTextWriter("person.xml", Encoding.Unicode);
serializer.Serialize(writer, p);

In the end we get a XML file person.xml which is contains:

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>I Made Krisna</name>

Note that XmlSerializer cannot worked for non-public classes and/or attributes so make sure the class have a property to access the non-public attributes.

One Thought on “Writing Object to XML using XmlSerializer C# Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation