C# 操作Xml之创建XML

C# 操作Xml之创建XML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace XML_Practice
{
    /// <summary>
    /// 使用dom的方式读取和写入xml文件
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            //在内存中创建一个dom对象
            XmlDocument xDoc = new XmlDocument();
            //声明一个文档说明
            XmlDeclaration xmlDeclaration = xDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            //将文档说明添加到dom对象中
            xDoc.AppendChild(xmlDeclaration);
            //创建一个跟节点
            XmlElement rootElement = xDoc.CreateElement("School");
            //把根节点添加到xDoc
            xDoc.AppendChild(rootElement);
            //创建一个子节点class
            XmlElement classElement = xDoc.CreateElement("class");
            //为class子节点创建一个id的属性
           XmlAttribute classId= xDoc.CreateAttribute("id");
            classId.Value = "cl01";
            //把classId属性挂在班级节点上
            classElement.Attributes.Append(classId);
            //把class子节点添加到scholl中
            rootElement.AppendChild(classElement);


            //再创建一个子节点叫做student
            XmlElement studentElement = xDoc.CreateElement("Student");
            //为Student类创建一个Id的属性
            XmlAttribute studentId = xDoc.CreateAttribute("Id");
            studentId.Value = "st01";
            //把studentId属性挂在student节点上
            studentElement.Attributes.Append(studentId);
            //把student节点挂在class节点的下面
            classElement.AppendChild(studentElement);

            //将dom对象写入到文件中
            xDoc.Save("standard.xml");
            Console.WriteLine("写入成功!");
            Console.ReadKey();


        }
    }
}


学习参考视频

发布了65 篇原创文章 · 获赞 8 · 访问量 3229

猜你喜欢

转载自blog.csdn.net/yasenRK/article/details/104085333