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(); } }
C# XML 序列化与反序列化
最新推荐文章于 2024-08-13 15:29:02 发布