web analytics

How to Serialize and Deserialize XML in C#?

Options

codeling 1602 - 6666
@2016-01-10 17:23:00

This posting describes how to serialize an object to XML and deserialize an object from XML in C#. This method is useful for persisting the state of an object and it is also useful for cloning an object by de-serializing the XML back to a new object.

XML Serialization

Serialization is the process of taking the state of an object and persisting it in some fashion. The Microsoft .NET Framework includes powerful objects that can serialize any object to XML. The System.Xml.Serialization namespace provides this capability.

This following C# code demonstrates how to serialize an employee object into XML ans write it a text file named "emp.xml".

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

namespace Serialize
{
    public class Employee
    {
        public string FirstName;
        public string LastName;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Employee p = new Employee();
            p.FirstName = "James";
            p.LastName = "Bond";

            //Serialization

            TextWriter writer = new StreamWriter("emp.xml");

            XmlSerializer serializer = new XmlSerializer(typeof(Employee));

            serializer.Serialize(writer, p);

            writer.Close();

        }

    }
}

The content in the file "emp.xml" is:

<?xml version="1.0" encoding="utf-8"?>
< Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>James</FirstName>
  <LastName>Bond</LastName>
< /Employee>

XML Deserialization

Deserialization is the process of reading an instance of an XML document and constructing an object that is strongly typed to the XML Schema (XSD) of the document. The System.Xml.Serialization namespace provides this capability.

Before deserializing, an XmlSerializer must be constructed using the type of the object that is being deserialized.

This following C# code demonstrates how to deserialize an employee object using a TextReader object which reads the above xml file "emp.xml":

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

namespace Deserialize
{
    public class Employee
    {
        public string FirstName;
        public string LastName;
    }

    class Program
    {
        static void Main(string[] args)
        {
             //Deserialization


            TextReader reader = new StreamReader("emp.xml");
            XmlSerializer serializer = new XmlSerializer(typeof(Employee));
            Employee p2 = (Employee)serializer.Deserialize(reader);
            reader.Close();

        }

    }
}

We can see the object in debug mode

:

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com