Serializing and Deserializing XML in .NET


XML still has a place in .NET, quite a big one, actually. With the coming of JSON, you tend to forget about XML and how powerful it could be. In this article, you will learn how to serialize and deserialize XML in .NET quickly and easily.


You will create a Console Application, so there is no need to design any buttons and so on. You can create the Console Application in either C# or Visual Basic.NET. After the project has been created, open any text editor and enter the following XML.


   <StudentSurname>du Preez</StudentSurname>
   <Course>Introduction to Computers</Course>

The preceding XML creates a student object with the StudentNumber, StudentName, StudentSurname, StudentAge, and Course Elements, along with their respective values. Obviously, you may enter as many students as you want, but I prefer to keep this exercise as simple as possible. Save the file as Student.xml.

Add the Student.xml file to your project by selecting Project, Add Existing item…, and then browsing for it. After the file has been added, your Solution Explorer would look like Figure 1.

Solution Explorer
Figure 1: Solution Explorer

Right-click now on your Student.xml File and select Properties. This will produce the Properties Window, shown in Figure 2. Ensure that the Build Action property is set to Content, and the Copy to Output Directory Property is set to Copy Always. This property ensures that the file will always be copied to your Bin folder.

Student.xml Properties
Figure 2: Student.xml Properties

Create a Student class and enter the following code:


   public class Student

      public string StudentNumber { get; set; }

      public string StudentName { get; set; }

      public string StudentSurname { get; set; }

      public string StudentAge { get; set; }

      public string Course { get; set; }



Public Class Student

   Public Property StudentNumber As String
   Public Property StudentName As String
   Public Property StudentSurname As String
   Public Property StudentAge As String
   Public Property Course As String

End Class

The Student Class contains the same elements as the Student.xml file does. This is important when serializing and deserializing files into and from objects. All the fields in the XML file have an element to which it can be connected to, thus the value being stored or retrieved.

Add the Serializer class and add the following code into it.


using System.IO;
using System.Xml.Serialization;
   public class Serializer
      public T Deserialize<T>(string input) where T : class
         XmlSerializer ser = new XmlSerializer(typeof(T));

         using (StringReader sr = new StringReader(input))
            return (T)ser.Deserialize(sr);

      public string Serialize<T>(T ObjectToSerialize)
         XmlSerializer xmlSerializer = new

         using (StringWriter textWriter = new StringWriter())
            xmlSerializer.Serialize(textWriter, ObjectToSerialize);
            return textWriter.ToString();



Imports System.IO
Imports System.Xml.Serialization

Public Class Serializer
   Public Function Deserialize(Of T As Class) _
         (ByVal input As String) As T

      Dim ser As XmlSerializer = New XmlSerializer(GetType(T))

      Using sr As StringReader = New StringReader(input)

         Return CType(ser.Deserialize(sr), T)

      End Using

   End Function

   Public Function Serialize(Of T)(ByVal ObjectToSerialize As T) _
         As String

      Dim xmlSerializer As XmlSerializer =_
         New XmlSerializer(ObjectToSerialize.[GetType]())

      Using textWriter As StringWriter = New StringWriter()

         xmlSerializer.Serialize(textWriter, ObjectToSerialize)

         Return textWriter.ToString()

      End Using

   End Function

End Class

In the Deserialize function, you make use of a StringReader object to populate the Student object. The Serialize method makes use of the StringWriter to copy the contents of the Student object into an XML file.

Add the code for the program's Main procedure.


using System;
using System.IO;
   class Program
      static void Main(string[] args)
         Serializer sSerialize = new Serializer();

         string strPath = string.Empty;
         string strInput = string.Empty;]
         string strOutput = string.Empty;

         strPath = Directory.GetCurrentDirectory() +
         strInput = File.ReadAllText(strPath);

         Student student = sSerialize.Deserialize<Student>
         strOutput = sSerialize.Serialize<Student>(student);







Imports System.IO

Module Module1

   Sub Main()

      Dim sSerialize As Serializer = New Serializer()

      Dim strPath As String = String.Empty
      Dim strInput As String = String.Empty
      Dim strOutput As String = String.Empty

      strPath = Directory.GetCurrentDirectory() & "\Student.xml"

      strInput = File.ReadAllText(strPath)

      Dim student As Student = _
         sSerialize.Deserialize(Of Student)(strInput)

      strOutput = sSerialize.Serialize(Of Student)(student)



   End Sub

End Module

You create a new Serializer object; then, you specify where to obtain the XML file you want to read. Lastly, you serialize the file and display the results inside the Command Prompt window (see Figure 3).

Figure 3: Running


XML is still very relevant. Because it is such an easy format to use, it is still quite popular. Knowing how to work with XML files properly is a vital skill to have, and I hope I have helped you learn a thing or two.

This article was originally published on November 8th, 2018

About the Author

Hannes DuPreez

Hannes du Preez is a self-taught developer who started learning to program in the days of QBasic. He has written several articles over the years detailing his programming quests and adventures. .NET is his second love, just after his wife and kid. He has always been an avid supporter of .NET since the beginning and is an expert in VB and C#. He was given the Microsoft Most Valuable Professional Award for .NET (2008–2017). He has worked as a moderator and an article reviewer on online forums and currently works as a C# developer and writes articles for CodeGuru.com, Developer.com, DevX.com, and the Database journal.
His first book Visual Studio 2019 In Depth is currently on sale on Amazon and Bpb Publications.

You could reach him at: ojdupreez1978[at]gmail[dot]com

Related Articles

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date