C# - Simple Write XmlSerializer

This snippet shows how to serialize a class into XML using the XmlSerializer Class.
  1. using System;
  2. using System.IO;
  3. using System.Xml.Serialization;
  4.  
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             Product Item1 = new Product();
  10.             Item1.Name = "Mp3 Player";
  11.             Item1.Price = 33.99;
  12.  
  13.             FileStream fStream = new FileStream("product.xml", FileMode.Create);
  14.             XmlSerializer xmlSerializer = new XmlSerializer(typeof(Product));
  15.             xmlSerializer.Serialize(fStream, Item1);
  16.             fStream.Close();
  17.             Console.WriteLine("Item1 has been serialized");
  18.             Console.ReadKey();
  19.         }
  20.     }
  21.  
  22.  
  23.     [System.Xml.Serialization.XmlRootAttribute()]
  24.     public class Product
  25.     {
  26.         private string name;
  27.         private double price;
  28.  
  29.         [XmlElement("Name")]
  30.         public string Name
  31.         {
  32.             set { this.name = value; }
  33.             get { return name; }
  34.         }
  35.  
  36.         [XmlElement("Price")]
  37.         public double Price
  38.         {
  39.             set { this.price = value; }
  40.             get { return price; }
  41.         }
  42.     }

No comments:

Post a Comment