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;
}
}