using System; using System.Xml.Serialization; // Define the class to be serialized [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } } // Serialize and Deserialize public class XmlSerializationExample { static void Main(string[] args) { // Serialize the object to XML Person person = new Person { Name = "John", Age = 30 }; XmlSerializer serializer = new XmlSerializer(typeof(Person)); serializer.Serialize(Console.Out, person); // Deserialize the XML back into the object string xmlString = @""; StringReader reader = new StringReader(xmlString); Person deserializedPerson = (Person)serializer.Deserialize(reader); } } John 30
using System; using System.IO; using System.Xml.Serialization; // Define classes to be serialized [Serializable] public class Order { [XmlAttribute] public int OrderId { get; set; } public ListIn this example, we define a more complex Order class that has a nested list of OrderItem objects. We use various XmlAttribute and XmlElement attributes to specify how we want the XML to be formatted when serialized. We also use the StreamWriter and StreamReader classes to write and read from a file instead of standard input and output. This example demonstrates more advanced usage of the XmlSerializer class for nested object serialization and deserialization. Package library: System.Xml.SerializationItems { get; set; } } [Serializable] public class OrderItem { public string ProductName { get; set; } public int Quantity { get; set; } public decimal Price { get; set; } } // Serialize and Deserialize public class XmlSerializationExample2 { static void Main(string[] args) { // Serialize the object to XML Order order = new Order { OrderId = 1000, Items = new List { new OrderItem { ProductName = "Product1", Quantity = 2, Price = 9.99M }, new OrderItem { ProductName = "Product2", Quantity = 1, Price = 20.99M } } }; XmlSerializer serializer = new XmlSerializer(typeof(Order)); using (TextWriter writer = new StreamWriter("order.xml")) { serializer.Serialize(writer, order); } // Deserialize the XML back into the object using (TextReader reader = new StreamReader("order.xml")) { Order deserializedOrder = (Order)serializer.Deserialize(reader); Console.WriteLine("Order ID: {0}", deserializedOrder.OrderId); foreach (OrderItem item in deserializedOrder.Items) { Console.WriteLine("Product: {0}, Quantity: {1}, Price: {2}", item.ProductName, item.Quantity, item.Price); } } } }