Search code examples
c#xmlserializationdeserializationxml-serialization

How to Mapping Deserialize XML document using c#


i am new to c # programming and i m stuck in how ot Deserialize this XML document, i have seen this tutorial How to Deserialize XML document and it was helpful but as you can see my XML contains more informations and he is more complex :

<?xml version="1.0" encoding="utf-8"?>
<Classrooms>
    <Classroom name="ClassroomA">
        <Students name = "John"/>
        <Students name = "Bryan"/>
        <Students name = "Eva"/>
    </Classroom>
    <Classroom name="ClassroomB">
        <Students name = "Harry"/>
        <Students name = "Emma"/>
        <Students name = "Joe"/>
    </Classroom>
    <Classroom name="ClassroomC">
        <Students name = "Lionnel"/>
        <Students name = "Rio"/>
        <Students name = "Eva"/>
    </Classroom>
</Classrooms>

My main goal is to create a Map of classrooms from my XML file :

example : Dictionnary<string,List> classrooms ,

Key 1 : classroomA, Values : John,Bryan,Eva

Key 2 : classroomB, Values : Harry,Emma,Joe

Key 3 : classroomC, Values : Lionnel,Rio,Eva

Thanks for help


Solution

  • Try following :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Xml.Linq;
    
    namespace ConsoleApplication178
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XmlReader reader = XmlReader.Create(FILENAME);
                XmlSerializer serializer = new XmlSerializer(typeof(Classrooms));
                Classrooms classrooms = (Classrooms)serializer.Deserialize(reader);
                reader.Close();
                //using xml linq
                XDocument doc = XDocument.Load(FILENAME);
                Dictionary<string, List<string>> dict = doc.Descendants("Classroom")
                    .GroupBy(x => (string)x.Attribute("name"), y => y)
                    .ToDictionary(x => x.Key, y => y.Elements("Students").Select(x => (string)x.Attribute("name")).ToList());
            }
        }
        public class Classrooms
        {
            [XmlElement()]
            public List<Classroom> Classroom { get; set; }
        }
        public class Classroom
        {
            [XmlAttribute]
            public string name { get; set; }
    
            [XmlElement()]
            public List<Students> Students { get; set; }
    
        }
        public class Students
        {
            [XmlAttribute]
            public string name { get; set; }
        }
    }