Mega Code Archive

 
Categories / C# / File Stream
 

Use XML Serialization with Custom Objects

using System; using System.Xml; using System.Xml.Serialization; using System.IO; public class SerializeXml {     private static void Main() {         CarList catalog = new CarList("New List", DateTime.Now.AddYears(1));         Car[] cars = new Car[2];         cars[0] = new Car("Car 1", 12342.99m);         cars[1] = new Car("Car 2", 21234123.9m);         catalog.Cars = cars;         XmlSerializer serializer = new XmlSerializer(typeof(CarList));         FileStream fs = new FileStream("CarList.xml", FileMode.Create);         serializer.Serialize(fs, catalog);         fs.Close();         catalog = null;         // Deserialize the order from the file.         fs = new FileStream("CarList.xml", FileMode.Open);         catalog = (CarList)serializer.Deserialize(fs);         // Serialize the order to the Console window.         serializer.Serialize(Console.Out, catalog);     } } [XmlRoot("carList")] public class CarList {     [XmlElement("catalogName")]     public string ListName;          // Use the date data type (and ignore the time portion in the serialized XML).     [XmlElement(ElementName="expiryDate", DataType="date")]     public DateTime ExpiryDate;          [XmlArray("cars")]     [XmlArrayItem("car")]     public Car[] Cars;     public CarList() {     }     public CarList(string catalogName, DateTime expiryDate) {         this.ListName = catalogName;         this.ExpiryDate = expiryDate;     } } public class Car {     [XmlElement("carName")]     public string CarName;          [XmlElement("carPrice")]     public decimal CarPrice;          [XmlElement("inStock")]     public bool InStock;          [XmlAttributeAttribute(AttributeName="id", DataType="integer")]     public string Id;     public Car() {     }     public Car(string carName, decimal carPrice) {         this.CarName = carName;         this.CarPrice = carPrice;     } }