C#控制台程序
一、Person.cs代码
using System.Linq;
using System.Text;using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace xml_Serializable
{
[Serializable]
public class Person
{
private string name;
//[XmlElement("userName")]
public string Name
{
get { return name; }
set { name = value; }
}
//[NonSerialized]
private int age;
//[XmlElement("userage")]
public int Age
{
get { return age; }
set { age = value; }
}
//[NonSerialized]
private string gender;
public string Gender
{
get { return gender; }
set { gender = value; }
}
public Person(string name, int age, string gender)
{
this.name = name;
this.age = age;
this.gender = gender;
}
public Person() { }
}
}
二、Program.cs代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace xml_Serializable
{
class Program
{
static void Main(string[] args)
{
#region ///XML序列化
List<Person> ps = new List<Person>();
Person[] p = { new Person("Jack", 23, "M"), new Person("Bruse", 24, "M") };
ps.AddRange(p);
using (FileStream fs = new FileStream(@"D:\data\usedata.xml", FileMode.Create, FileAccess.Write))
{
//在进行XML序列化的时候,在类中一定要有无参数的构造方法(要使用typeof获得对象类型)
XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Person>));
xmlFormat.Serialize(fs, ps);
}
Console.WriteLine("OK!");
Console.Read();
#endregion
#region///XML反序列化
using (FileStream fs = new FileStream(@"D:\data\usedata.xml", FileMode.Open, FileAccess.Read))
{
XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Person>));
List<Person> lsPs = (List<Person>)xmlFormat.Deserialize(fs);
foreach (Person p in lsPs)
{
Console.WriteLine(p.Name);
}
Console.Read();
}
#endregion
}
}
}