C# 两种方法创建XML文件

首次发布:2017-07-23 20:29
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace XML文件创建
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        List<Penson> list = new List<Penson>();
        public void PensonValue()
        {

            list.Add(new Penson { name = "罗分明", age = 18, gender = "男" });
            list.Add(new Penson { name = "lqwvje", age = 19, gender = "男" });
            list.Add(new Penson { name = "LFM", age = 20, gender = "男" });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //.net2.0方方法
            PensonValue();
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
           
            XmlElement list1 = doc.CreateElement("list");
            doc.AppendChild(list1);

            for (int i = 0; i < list.Count; i++)
            {
                XmlElement xmlName = doc.CreateElement("name");
                xmlName.SetAttribute("id", i.ToString());//添加属性
                xmlName.InnerText = list[i].name;
                list1.AppendChild(xmlName);

                XmlElement xmlAge = doc.CreateElement("age");
                xmlAge.InnerText = (list[i].age).ToString();
                list1.AppendChild(xmlAge);

                XmlElement xmlGender = doc.CreateElement("gender");
                xmlGender.InnerText = list[i].gender;
                list1.AppendChild(xmlGender);
            }
            doc.Save("xml1.xml");
            MessageBox.Show("ok");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //.net 4.0方法
            PensonValue();
            XDocument doc = new XDocument();
            XDeclaration dec = new XDeclaration("1.0", "utf-8", null);
            doc.Declaration = dec;
            XElement list1 = new XElement("list");
            doc.Add(list1);
            for(int i = 0; i < list.Count; i++)
            {
                list1.SetElementValue("name", list[i].name);
                list1.SetElementValue("age", list[i].age);
                list1.SetElementValue("gender", list[i].gender);
                list1.Add(list1);
            }
            doc.Save("X1.xml");
            MessageBox.Show("ok");
            
        }
    }
    public class Penson
    {
        public string name { get; set; }
        public int age { get; set; }
        public string gender { get; set; }
    }
}