In previous article, I mentioned Convert EPOC (Unix) time stamp to Datetime and Vice-Versa in C# but in this article, I have mentioned how to Deserialize XML string to Object in C# or you can say we will convert XML string to C# object, using Console application example.
Step 1: Create a new console application project in Visual Studio, by opening VS 2022/2019, click on "Create new project", then select "Console application" -> Name your project and then select ".NET Core" Version, I am using .NET 5.
Step 2: Now, we will create our sample class for which we will deserialize XML string, so here is the C# class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace XMlToCsharpObject
{
[XmlRoot("StudentList")]
public class StudentList
{
[XmlElement("Student")]
public List<Student> Students { get; set; }
}
public class Student
{
public string Name { get; set; }
public string Class { get; set; }
}
}
In the above C# class, we created StudentList and mentioned Root Element as StudentList, while XML Element would be Student.
Step 3: Considering above Class, we can have XML like below, which we want to deserialize
<StudentList>
<Student>
<Name>Vikas</Name>
<Class>Class X</Class>
</Student>
<Student>
<Name>Vikram</Name>
<Class>Class X</Class>
</Student>
</StudentList>
so, the complete console application example would be as below
using System;
using System.IO;
using System.Xml.Serialization;
namespace XMlToCsharpObject
{
internal class Program
{
static void Main(string[] args)
{
string sampleXML = @"<StudentList>
<Student>
<Name>Vikas</Name>
<Class>Class X</Class>
</Student>
<Student>
<Name>Vikram</Name>
<Class>Class X</Class>
</Student>
</StudentList>";
XmlSerializer serializer = new XmlSerializer(typeof(StudentList));
using (TextReader reader = new StringReader(sampleXML))
{
var result = (StudentList)serializer.Deserialize(reader);
Console.WriteLine("First Student name :" + result.Students[0].Name);
}
}
}
}
Once, we will build the above code and run you will get the output as the first student name
First Student name :Vikas
I hope it helps.
You may also like to read:
How to add time in datetime in C#?
convert string to datetime in C#
Show tabs and spaces in Visual studio code