追加xml文档

陌路散爱 提交于 2019-12-27 14:05:04

实现代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
namespace _04追加XML文档
{
    class Program
    {
        static void Main(string[] args)
        {
            //1)创建xml文档对象\
            XmlDocument doc = new XmlDocument();

            XmlElement books;
            if (File.Exists("Books.xml"))
            {
                //如果文件存在
                doc.Load("Books.xml");
                //获取根节点
                books = doc.DocumentElement;
            }
            else//如果文件不存在
            {
                //创建第一行
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                //创建第一行
                books = doc.CreateElement("Books");
                doc.AppendChild(books);
            }
            //5、给节点Books创建节点
            XmlElement book1 = doc.CreateElement("Book1");
            books.AppendChild(book1);
            //6、给Book1添加子节点
            XmlElement name1 = doc.CreateElement("Name");
            name1.InnerText = "C#";
            book1.AppendChild(name1);
            XmlElement price1 = doc.CreateElement("Price");
            price1.InnerText = "10";
            book1.AppendChild(price1);
            //5.2、给节点Books创建节点
            XmlElement book2 = doc.CreateElement("Book2");
            books.AppendChild(book2);
            //6.2 给Book2添加子节点
            XmlElement name2 = doc.CreateElement("Name2");
            name2.InnerText = "真心累";
            book2.AppendChild(name2);
            doc.Save("Books.xml");
            //保存
            Console.WriteLine("保存成功");
            Console.ReadKey();
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!