天天@BLOG

脖子越来越疼,脑袋越来越钝
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

XML序列化与反序列化

Posted on 2006-07-23 09:22  天天在线  阅读(383)  评论(0编辑  收藏  举报

using System;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Text;

namespace ConsoleApplication4
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 class Customers
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args) {
   Customer customer = Customers.GetGustomer();
   SerializerCustomer1(customer);
   SerializerCustomer2(customer);
   SerializerCustomer3(customer);

   Console.ReadLine();
  }

  public static Customer GetGustomer() {
   Customer customer = new Customer();
   Address address = new Address();
   address.City = "北京";
   address.State = "丰台";
   address.Street = "马家堡西里";
           
   customer.Address = address;
   customer.Name = "BillChen";

   return customer;
  }

  private static void SerializerCustomer1(Customer customer) {
   XmlSerializer ser = new XmlSerializer(typeof(Customer));
   FileStream stream = new FileStream("test.xml", FileMode.OpenOrCreate);

   ser.Serialize( stream, customer );

   stream.Close();
  }

  private static void SerializerCustomer2(Customer customer) {
   XmlSerializer ser = new XmlSerializer(typeof(Customer));
           
   MemoryStream stream = new MemoryStream(100);
   ser.Serialize( stream, customer );

   stream.Position = 0;
   using(StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {

    Console.Write(reader.ReadToEnd());


   }
  }

  private static void SerializerCustomer3(Customer customer) {
   XmlSerializer ser = new XmlSerializer(typeof(Customer));
           
   MemoryStream stream = new MemoryStream(100);
   XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
   writer.Formatting = Formatting.Indented;//缩进
   ser.Serialize( writer, customer );

   stream.Position = 0;
   using(StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
    string line;
    while((line = reader.ReadLine()) != null) {
     Console.WriteLine(line);
    }
   }
   writer.Close();
  }
 }
 [Serializable]
 public class Address {
  public Address(){}


  public string Street {
   get { return street; }
   set { street = value; }
  }private string street;

  public string City {
   get { return city; }
   set { city = value; }
  }private string city;

  public string State {
   get { return state; }
   set { state = value; }
  }private string state;
 }

 [Serializable]
 public class Customer {
  public Customer(){}

  public string Name {
   get { return name; }
   set { name = value; }
  }private string name;

  public Address Address {
   get { return address; }
   set { address = value; }
  }private Address address;
 }
}

@忙碌,不代表有效率;方法,远胜于苦干