实现代码:
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();
}
}
}
来源:CSDN
作者:360不解释
链接:https://blog.csdn.net/qq_42777375/article/details/103726126