手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

VS2010怎么实现C#的xml文件的编写

时间:2024-10-11 21:42:06

1、我们在VS中新建一个工程,然后新建一个XMLHelper的类,这个类中有一个静态函数 Serizer 专门用来处理XML序列化的public class XMlHelper { public static void Serizer<T>(T t,string fileName) { XmlTextWriter textWriter = new XmlTextWriter(fileName,Encoding.UTF8); XmlSerializer xml = new XmlSerializer(t.GetType()); xml.Serialize(textWriter, t); textWriter.Flush(); textWriter.Close(); } }

VS2010怎么实现C#的xml文件的编写

2、我们在新建一个PerSon类,和一个Book类,用来存储序列化的内容 public class Person { public int Age { get; set; } public string Name { get; set; } public List<Book> books { get; set; } } public class Book { public Book() { } public string Name { get; set; } public int Price { get; set; } }注意Book中要有显式无参构造函数,不然无法序列化List集合

VS2010怎么实现C#的xml文件的编写

3、最后再在主函数中写入 static void Main(string[] args) { Person person = new Person() { Age = 20, Name = "正三", books = new List<Book>() { new Book(){ Price=20, Name="好好学习" }, new Book(){ Price=30, Name="不好学习" } } }; XMlHelper.Serizer<Person>(person, "person.xml"); }

VS2010怎么实现C#的xml文件的编写

4、运行程序,就可得到序列化的XML文件了

VS2010怎么实现C#的xml文件的编写

5、如果有什么疑问,或者需要源码,或者遇到了其他的坑,都可以给我留言评论,我会尽量解答的。

© 手抄报圈