- Course
- Data serialization
- XmlSerialization: Serialize objects
 
 
                    
                        
XmlSerialization: Serialize objects
                    
                    
                    
                        Last updated: 
                            8/23/2020
                        
                      
                        
                            ⁃
                            Difficulty: 
                            Intermediate
                        
                    
           
                    Create a C# program to serialize and deserialize objects in XML format. To do this you can use the XmlSerialization class included in the System.Xml.Serialization namespace. 
First implement a Person class with three properties (Name, Age and City). The City class will have two properties (Name and Population). Then create a person object and use the XmlSerialization object serializer to save the data in an xml file, later deserialize the file and print it on screen. Remember to prepare a ToString() method to print the Persona class.
                    
                    Input
                    
                    
                    
                    Output
                    
                    
                    Solution
                    
                   
                    
                    using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
public class XmlSerialization
{
    static string nameFile = "out.xml";
    public static void Main(string[] args)
    {
        Person person = new Person(){ Name = "Nauj", Age = 26, City = new City(){ Name = "Spain", Population = 13456766 } };
        Serialize(person);
        person = Deserialize();
        Console.WriteLine(person.ToString());
    }
    public static void Serialize(Person p)
    {
        XmlSerializer ser = new XmlSerializer(typeof(Person));
        using (TextWriter writer = new StreamWriter(nameFile))
        {
            ser.Serialize(writer, p);
        }       
    }
    public static Person Deserialize()
    {
        Person p;
        XmlSerializer ser = new XmlSerializer(typeof(Person));
        using (TextReader reader = new StreamReader(nameFile))
        {
             p = (Person)ser.Deserialize(reader);
        }
        return p;
    }
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public City City { get; set; }
        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine("Name: " + Name);
            str.AppendLine("Age: " + Age);
            str.AppendLine("City: " + City.Name);
            return str.ToString();
        }
    }
    public class City
    {
        public string Name { get; set; }
        public int Population { get; set; }
    }
}