<1>LinktoXML
代码namespace LinktoXML { class Program { static void Main(string[] args) { //1.创建一个XML文档 XDocument XDoc = new XDocument(); //2.添加根节点 XElement 元素 XElement XRoot = new XElement("Root"); //需要写入根节点名 XDoc.Add(XRoot); //创建一个省加入到Root中 XElement xProvince = new XElement("Province"); XRoot.Add(xProvince); //创建省名,位置,省会加入到xProvince中 XElement xName = new XElement("Name"); XElement xLocation = new XElement("Location"); XElement xPcaptial = new XElement("Captial"); xName.Value = "江苏"; xLocation.Value = "东部"; xPcaptial.Value = "南京"; xProvince.Add(xName, xLocation, xPcaptial); //为 xProvince添加属性 XAttribute xNum = new XAttribute("ID", "001"); xProvince.Add(xNum); //保存XML文档 XDoc.Save(@"F:\myxml.xml"); } } }
<2>XML序列化
代码namespace XML序列化 { class Program { static void Main(string[] args) { List<Person> perList = new List<Person>() { new Person(){ Name="董超 ",Age=19, Gender='男'}, new Person(){ Name="周杰伦",Age=30, Gender='男'}, new Person(){ Name="蔡依林",Age=28, Gender='女'} }; using (FileStream file = new FileStream("序列化xml.xml", FileMode.Create, FileAccess.Write)) { XmlSerializer ser = new XmlSerializer(typeof(List<Person>)); ser.Serialize(file, perList); } } } [Serializable] public class Person { string name; public string Name { get { return name; } set { name = value; } } int age; public int Age { get { return age; } set { age = value; } } char gender; public char Gender { get { return gender; } set { gender = value; } } public Person() { } } }