Serializing and Deserializing XML in .NET

Introduction

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 de-serialize XML in .NET quickly and easily.

Practical

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. Consider visiting the TechRepublic Academy to hone your C# skills. There are dozens of lessons from introductions to C#, to advanced lessons. After the project has been created, open any text editor and enter the following XML.

XML

<Student>
   <StudentNumber>12345</StudentNumber>
   <StudentName>Hannes</StudentName>
   <StudentSurname>du Preez</StudentSurname>
   <StudentAge>40</StudentAge>
   <Course>Introduction to Computers</Course>
</Student>

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:

C#

   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; }

   }

VB.NET

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.

C#

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
            XmlSerializer(ObjectToSerialize.GetType());

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

   }

VB.NET

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.

C#

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() +
            @"\Student.xml";]
         strInput = File.ReadAllText(strPath);

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

         Console.WriteLine(student.StudentName);

         Console.WriteLine(strOutput);

         Console.ReadKey();

      }

   }

VB.NET

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)

      Console.WriteLine(student.StudentName)
      Console.WriteLine(strOutput)

      Console.ReadKey()]

   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).

Running
Figure 3: Running

Conclusion

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.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read