C# - Simple Read XmlSerializer

This snippet shows how to read a serialized XML file 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;
  10.  
  11.  
  12.             FileStream fStream = new FileStream("product.xml", FileMode.Open);
  13.             XmlSerializer xmlSerializer = new XmlSerializer(typeof(Product));
  14.             Item1 = (Product)xmlSerializer.Deserialize(fStream);
  15.             Console.WriteLine("Item1: Name:" + Item1.Name);
  16.             Console.WriteLine("Item1: Price:" + Item1.Price);
  17.             fStream.Close();
  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.  
  43.     }
  44.  

No comments:

Post a Comment