c# 创建XML文档

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace _02创建一个XML文档
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);

            XmlElement person = doc.CreateElement("Person");
            doc.AppendChild(person);

            XmlElement student1 = doc.CreateElement("Student");
            student1.SetAttribute("ID", "1");
            person.AppendChild(student1);

            XmlElement name1 = doc.CreateElement("Name");
            name1.InnerText = "刘德华";
            student1.AppendChild(name1);

            XmlElement age1 = doc.CreateElement("Age");
            age1.InnerText = "60";
            student1.AppendChild(age1);

            XmlElement gender1 = doc.CreateElement("Gender");
            gender1.InnerText = "";
            student1.AppendChild(gender1);



            XmlElement student2 = doc.CreateElement("Student");
            student2.SetAttribute("ID", "2");
            person.AppendChild(student2);

            XmlElement name2 = doc.CreateElement("Name");
            name2.InnerText = "张学友";
            student2.AppendChild(name2);

            XmlElement age2 = doc.CreateElement("Age");
            age2.InnerText = "60";
            student2.AppendChild(age2);

            XmlElement gender2 = doc.CreateElement("Gender");
            gender2.InnerText = "";
            student2.AppendChild(gender2);




            XmlElement student3 = doc.CreateElement("Student");
            student3.SetAttribute("ID", "3");
            person.AppendChild(student3);

            XmlElement name3 = doc.CreateElement("Name");
            name3.InnerText = "黎明";
            student3.AppendChild(name3);

            XmlElement age3 = doc.CreateElement("Age");
            age3.InnerText = "40";
            student3.AppendChild(age3);

            XmlElement gender3 = doc.CreateElement("Gender");
            gender3.InnerText = "";
            student3.AppendChild(gender3);


            doc.Save("person.xml");
            Console.WriteLine("保存成功");
            Console.ReadKey();

        }
    }
}

 

posted on 2017-06-13 15:44  算顺网  阅读(270)  评论(0编辑  收藏  举报

导航