How to read/import XML file contents to C# object?


Some times we just need to read/import XML file contents to C# object.

So let’s see how to do that.

We already know how to save or export C# object data to XML file

Creating XML file

let’s create xml file with some data as follows

XML file
<?xml version="1.0"?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Employee>
    <Id>1</Id>
    <Name>Venki Chikkanti</Name>
    <Dept>Development</Dept>
  </Employee>
  <Employee>
    <Id>2</Id>
    <Name>Matt</Name>
    <Dept>Management</Dept>
  </Employee>
  <Employee>
    <Id>3</Id>
    <Name>Mark</Name>
    <Dept>Transport</Dept>
  </Employee>
</ArrayOfEmployee>

Next we have to create C# class as follows

C# object
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Dept { get; set; }
}

Now let’s deserialize XML data and store into C# object and display as follows

Deserializing XML data to C#
static void Main(string[] args)
{
    var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//XMLData.xml";
    List<Employee> emps = new List<Employee>();
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load(path);
    string xmlString = xmlDocument.OuterXml;
    using (StringReader read = new StringReader(xmlString))
    {
        Type outType = typeof(List<Employee>);
        XmlSerializer serializer = new XmlSerializer(outType);
        using (XmlReader reader = new XmlTextReader(read))
        {
            emps = (List<Employee>)serializer.Deserialize(reader);
            reader.Close();
        }
        read.Close();
    }
    foreach (var item in emps)
    {
        Console.WriteLine(item.Id + " " + item.Name + " " + item.Dept);
    }
}

 

Deserialization XML to C#

Total Code:

Total Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    public class Class2
    {
        static void Main(string[] args)
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//XMLData.xml";
            List<Employee> emps = new List<Employee>();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(path);
            string xmlString = xmlDocument.OuterXml;
            using (StringReader read = new StringReader(xmlString))
            {
                Type outType = typeof(List<Employee>);
                XmlSerializer serializer = new XmlSerializer(outType);
                using (XmlReader reader = new XmlTextReader(read))
                {
                    emps = (List<Employee>)serializer.Deserialize(reader);
                    reader.Close();
                }
                read.Close();
            }
            foreach (var item in emps)
            {
                Console.WriteLine(item.Id + " " + item.Name + " " + item.Dept);
            }
        }
        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Dept { get; set; }
        }
    }
}

How to save/export serializable C# object to XML file?


Some times we just need to save/export C# object to XML file.

So let’s see how to do that.

Creating C# Object

First we need to create C# class as follows

Employee Class
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Dept { get; set; }
}

Next we have to create object of the above class and fill it with data as follows

Employee Object with data
List<Employee> emps = new List<Employee>();
emps.Add(new Employee { Id = 1, Name = “Venki Chikkanti”, Dept = “Development” });
emps.Add(new Employee { Id = 1, Name = “Matt”, Dept = “Management” });
emps.Add(new Employee { Id = 1, Name = “Mark”, Dept = “Transport” });

Now let’s serialize this data and store into xml file as follows.

Save to XML file
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + “//XMLData.xml”;
System.IO.FileStream file = System.IO.File.Create(path);

writer.Serialize(file, emps);
file.Close();

So the file will be saved to MyDocuments folder with filename as XMLData.

Output File content:

XML File
<?xml version=1.0?>
<ArrayOfEmployee xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema>
<Employee>
<Id>1</Id>
<Name>Venki Chikkanti</Name>
<Dept>Development</Dept>
</Employee>
<Employee>
<Id>1</Id>
<Name>Matt</Name>
<Dept>Management</Dept>
</Employee>
<Employee>
<Id>1</Id>
<Name>Mark</Name>
<Dept>Transport</Dept>
</Employee>
</ArrayOfEmployee>

tOtAL cOdE:

Total Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleWorks
{
public class CSharpObjToXMLFile
{
static void Main(string[] args)
{
List<Employee> emps = new List<Employee>();
emps.Add(new Employee { Id = 1, Name = “Venki Chikkanti”, Dept = “Development” });
emps.Add(new Employee { Id = 1, Name = “Matt”, Dept = “Management” });
emps.Add(new Employee { Id = 1, Name = “Mark”, Dept = “Transport” });

System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + “//XMLData.xml”;
System.IO.FileStream file = System.IO.File.Create(path);

writer.Serialize(file, emps);
file.Close();
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Dept { get; set; }
}
}
}