C# XML 序列化与反序列化

XML序列化为实体类,和实体类反序列化为XML并写入文件。

      [XmlAttribute("id")]意思是将这个字段作为xml的属性,属性名跟在“”中
      [XmlElement]意思是将这个字段做为xml的元素。 

 [Serializable]

    public class book

    {

        [XmlAttribute("id")]

        public string id { get; set; }

        [XmlAttribute("type")]

        public string type { get; set; }

        [XmlElement]

        public string bookName { get; set; }

        [XmlElement]

        public string author { get; set; }

        [XmlElement]

        public string ISBN { get; set; }

        [XmlElement]

        public double price { get; set; }

        [XmlElement]

        public int quantity { get; set; }

    }



 public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            basePath = System.Environment.CurrentDirectory.Replace(@"bin\Debug", "");

        }



        //项目路径

        public readonly string basePath;

        private void btnSerializer_Click(object sender, EventArgs e)

        {

            try

            {

                //获取当前目录

                string basePath = System.Environment.CurrentDirectory.Replace(@"bin\Debug", "");

                FileStream fs = new FileStream(basePath + "test.xml", FileMode.Open);



                //将对象序列化到XML文档中或从XML文档反序列对象。

                XmlSerializer sr = new XmlSerializer(typeof(List<book>));

                List<book> bs = (List<book>)sr.Deserialize(fs);

                bs.ForEach(m => MessageBox.Show(m.bookName));

                fs.Close();

            }

            catch (Exception ex)

            {



            }

        }



        private void btnFan_Click(object sender, EventArgs e)

        {

            List<book> stuList = new List<book>();

            stuList.Add(new book() { author = "罗贯中", id = "1", bookName = "三国演义", ISBN = "SGYY", price = 100.00, quantity = 10, type = "教育" });

            stuList.Add(new book() { author = "吴承恩", id = "1", bookName = "西游记", ISBN = "SGYY", price = 100.00, quantity = 10, type = "教育" });

            stuList.Add(new book() { author = "施耐庵", id = "1", bookName = "水浒传", ISBN = "SGYY", price = 100.00, quantity = 10, type = "教育" });

            stuList.Add(new book() { author = "曹雪芹", id = "1", bookName = "红楼梦", ISBN = "SGYY", price = 100.00, quantity = 10, type = "教育" });

            XmlSerializer ser = new XmlSerializer(typeof(List<book>));

            FileStream stream = File.Create("C:\\x.xml");

            ser.Serialize(stream, stuList);

            stream.Close();

        }

    }










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值