C#学习记录(八) XML Serializer尝试

将数据转为xml并写入文件

static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer>(){
                    new Customer() { FirstName = "Vars", LastName = "Hoo", Email = "vv@yahoo.com"},
                    new Customer() { FirstName = "Tes", LastName = "Qerr", Email = "tes123@qq.com"},
                    new Customer() { FirstName = "Hum", LastName = "Ltx", Email = "hl@163.com"}
            };

            XmlSerializer serializer = new XmlSerializer(typeof(List<Customer>));

            StreamWriter file = new StreamWriter(@"f:\test.xml");
            serializer.Serialize(file, customers);
        }

运行后相应位置的文件

如果更改Customer类中的内容

public class Customer
    {
        [XmlAttribute()]
        public string FirstName { get; set; }
        [XmlIgnore()]
        public string LastName { get; set; }
        public string Email { get; set; }

        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail: {2}", FirstName, LastName, Email);
        }
    }

输出的文件中的内容变为

 

接下来利用先前生成的test.xml文件,将其内容读入

static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Customer>));

            StreamReader file = new StreamReader(@"f:\test.xml");

            List<Customer> customers = serializer.Deserialize(file) as List<Customer>;
        }

posted on 2015-04-27 10:43  Zany丶  阅读(154)  评论(0编辑  收藏  举报

导航