Create a Java 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.
XmlSerialization
System.Xml.Serialization
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.
ToString()
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; } } }
Click here to view the exercise solution
Share it on your social media and challenge your friends to solve programming problems. Together, we can learn and grow.
The code has been successfully copied to the clipboard.
Continue improving your Java programming skills with our selection of practical exercises from the lesson. Click on Practice and challenge your knowledge!
Create a Java program to serialize and deserialize objects in binary format.
Create a Java program to serialize and deserialize objects in XML format.
Create a Java program that serialize and deserialize objects in JSON format.
Create a Java program to serialize and deserialize objects in JSON format.
Practice with exercises in Java to serialize arrays or objects in different ways. Learn how to serialize and deserialize the information later.
Free programming course with practical exercises and solutions in C#. Start learning right now!
Take your Exercises C# lessons everywhere with our Android app. Download it now from Google Play
Own and third party cookies to improve our services. If you go on surfing, we will consider you accepting its use.