dcsimg

WEBINAR:
On-Demand

Virtual Developer Workshop: Containerized Development with Docker


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



About the Author

Hannes DuPreez

Hannes du Preez is an ex MVP for Visual Basic from 2008 to 2017. He loves technology and loves Visual Basic and C#. He loves writing articles and proving that Visual Basic is more powerful than what most believe. You are most welcome to reach him at: ojdupreez1978[at]gmail[dot]com

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

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