C# 代码方式简单编写XML文档

XML文件可以用来存储简单的数据,它相当于一个简单的数据库。

下面就用C# 代码编写简单的XML文档


首先看一下XML文档的组成部分
在这里插入图片描述
他至少需要第一行的描述信息和根节点!
子节点可有可无。

创建XML文档

  1. 引入命名空间
    using System.Xml;

  2. 创建XML文档对象
    XmlDocument doc = new XmlDocument();

  3. 创建第一行的描述信息,并添加到XML文件中
    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
    doc.AppendChild(dec); // 并添加到XML文件中

  4. 创建根节点
    XmlElement books = doc.CreateElement("Books");
    将根节点添加到文档中
    doc.AppendChild(books);

  5. 给根节点Books添加子节点(请看下一个标题内容)

  6. 给book1添加子节点(请看下一个标题内容)

  7. 保存文档
    doc.Save("Books.Xml");

static void Main(string[] args) {

	// 通过代码创建XML文档
	// 1.引入命名空间
	// using System.Xml;

	// 2. 创建XML文档对象
	XmlDocument doc = new XmlDocument();

	// 3. 创建第一行的描述信息,并添加到XML文件中
	XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
	doc.AppendChild(dec);

	// 4. 创建根节点
	XmlElement books = doc.CreateElement("Books");
	// 将根节点添加到文档中
	doc.AppendChild(books);


         
	// 7. 保存
	doc.Save("Books.xml");
	Console.WriteLine("保存成功!");

	Console.ReadKey();
}

给XML文档添加节点元素

  1. 给根节点Books添加子节点
    XmlElement book1 = doc.CreateElement("Book"); // Element [ˈelɪmənt]
    将book1添加到根节点
    books.AppendChild(book1);

  2. 给book1添加子节点
    XmlElement name1 = doc.CreateElement("Name");
    设置name1的文本
    name1.InnerText = "水浒传"; // Inner [ˈɪnər] 内部的
    将Name添加到book1中
    book1.AppendChild(name1);

#region 水浒传

// 5. 给根节点Books添加子节点
XmlElement book1 = doc.CreateElement("Book");   // Element [ˈelɪmənt]
// 将book1添加到根节点
books.AppendChild(book1);

// 6.给book1添加子节点
XmlElement name1 = doc.CreateElement("Name");
// 设置name1的文本
name1.InnerText = "水浒传";    // Inner [ˈɪnər] 内部的
// 将Name添加到book1中
book1.AppendChild(name1);

XmlElement price1 = doc.CreateElement("Price");
price1.InnerText = "10元";
book1.AppendChild(price1);

XmlElement des1 = doc.CreateElement("Des");
des1.InnerText = "108个拆迁户";
book1.AppendChild(des1);

#endregion

XML添加属性值

定义好节点后就可以给节点添加属性值了

XmlElement orderItem1 = doc.CreateElement("OrderItem");
// 给节点添加属性
orderItem1.SetAttribute("Name", "阿猫");
orderItem1.SetAttribute("Count", "10");
items.AppendChild(orderItem1);

效果图:
在这里插入图片描述

代码展示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace 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 order = doc.CreateElement("Order");
            doc.AppendChild(order);

            XmlElement customerName = doc.CreateElement("CustomerName");
            customerName.InnerText = "周杰伦";
            order.AppendChild(customerName);

            XmlElement customerNumber = doc.CreateElement("CustomerNumber");
            customerNumber.InnerText = "007";
            order.AppendChild(customerNumber);

            XmlElement items = doc.CreateElement("Items");
            order.AppendChild(items);

            XmlElement orderItem1 = doc.CreateElement("OrderItem");
            // 给节点添加属性
            orderItem1.SetAttribute("Name", "阿猫");
            orderItem1.SetAttribute("Count", "10");
            items.AppendChild(orderItem1);

            XmlElement orderItem2 = doc.CreateElement("OrderItem");
            // 给节点添加属性
            orderItem2.SetAttribute("Name", "阿狗");
            orderItem2.SetAttribute("Count", "20");
            items.AppendChild(orderItem2);



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

            Console.ReadKey();
        }
    }
}

往XML文档追加元素

创建好XML文档对象后,我们需要先判断需要追加的文档是否存在,则需要加载当前文档进来,然后再获取到根节点对象;文档不存在,则创建文档的第一行描述信息,然后再创建根节点。

所以说,不管文档存不存在,我们都得需要获取到根节点。

效果图:
在这里插入图片描述

代码展示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;

namespace 追加XML {
    class Program {
        static void Main(string[] args) {

            // 追加XML文档

            // 1.添加命名空间
            // using System.Xml;

            // 2.先定义XML文档对象
            XmlDocument doc = new XmlDocument();
            XmlElement books;   // 根节点对象

            // 3. 判断文件是否存在
            if (File.Exists("attribute.xml")) {
                // 如果存在,加载XML文档
                doc.Load("attribute.xml");

                // 获得根节点
                books = doc.DocumentElement;
            } else {
                // 如果不存在
                // 创建XML文档第一行
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);

                // 创建根节点
                books = doc.CreateElement("Books");
                doc.AppendChild(books);
            }


            XmlElement book = doc.CreateElement("Book");
            books.AppendChild(book);

            XmlElement name = doc.CreateElement("Name");
            name.InnerText = "C#从还没入门到放弃";
            book.AppendChild(name);

            XmlElement price = doc.CreateElement("Price");
            price.InnerText = "110";
            book.AppendChild(price);

            XmlElement description = doc.CreateElement("Descroption");
            description.InnerText = "工地搬砖爽歪歪";
            book.AppendChild(description);


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

            Console.ReadKey();
        }
    }
}

读取XML文档中的元素

两种方式:

  1. 通过根节点获得子节点的集合,进行遍历输出;
  2. 通过根节点直接获得对应节点的集合,进行遍历输出。

效果图 与 运行截图:
在这里插入图片描述

在这里插入图片描述

代码展示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;

namespace 读取XML文档 {
    class Program {
        static void Main(string[] args) {

            XmlDocument doc = new XmlDocument();

            if (!File.Exists("Books.xml")) {
                // 如果文件不存在
                Console.WriteLine("文件不存在");
                Console.ReadKey();
                return;
            }

            // 加载XML文档
            doc.Load("Books.xml");

            // 获得根节点
            XmlElement books = doc.DocumentElement;

			
			/****方式二****/     

            // 直接获得对应的节点集合
            XmlNodeList xlnn = books.SelectNodes("/Books/Book");

            //Console.WriteLine(xlnn[0]["Name"].InnerText);
            foreach (XmlNode item in xlnn) {
                Console.WriteLine(item["Name"].InnerText);
                Console.WriteLine(item["Price"].InnerText);
                Console.WriteLine(item["Descroption"].InnerText);
            }

			
			/****方式二一****/     
				
            // 获得子节点,返回节点的集合
            //XmlNodeList xnl = books.ChildNodes;

            //foreach (XmlElement xe in xnl) {
            //    foreach (XmlElement item in xe.ChildNodes) {
            //        Console.WriteLine(item.InnerText);
            //    }
            //}

            Console.ReadKey();
        }
    }
}

读取带属性的XML文档

只是读取属性中的元素。

先获得对应的集合,然后再遍历输出即可。

效果图 和 运行截图:
在这里插入图片描述

在这里插入图片描述

代码展示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;

namespace 读取带属性的XML文档 {
    class Program {
        static void Main(string[] args) {

            XmlDocument doc = new XmlDocument();
            string path = "attribute.xml";

            if (!File.Exists(path)) {
                Console.WriteLine("文件不存在");
                Console.ReadKey();
                return;
            }

            doc.Load(path);

            // 获取到设置属性的值
            XmlNodeList xnl = doc.SelectNodes("/Order/Items/OrderItem");

            foreach (XmlNode xn in xnl) {
                Console.WriteLine(xn.Attributes["Name"].Value);
                Console.WriteLine(xn.Attributes["Count"].Value);
            }

            Console.ReadKey();
        }
    }
}

删除节点

加载文档后,获得对应的节点,然后进行删除。

运行代码前:
在这里插入图片描述

运行代码后:
在这里插入图片描述

代码展示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;

namespace 删除节点 {
    class Program {
        static void Main(string[] args) {
            XmlDocument doc = new XmlDocument();
            string path = "Books.xml";

            if (!File.Exists(path)) {
                Console.WriteLine("文件不存在");
                Console.ReadKey();
                return;
            }

            doc.Load(path);

            // 获得需要删除的节点
            XmlNode xn =  doc.SelectSingleNode("/Books/Book");

            // 删除一个节点中的全部元素
            xn.RemoveAll(); // 按照顺序从第一个开始删除
            

            //doc["Books"].RemoveAll(); // 移除Books标签里面的所有元素

            //doc.DocumentElement.RemoveChild(xn);  // 等效于 xn.RemoveAll();

            doc.Save(path);
            Console.WriteLine("删除成功");
            Console.ReadKey();
        }
    }
}

总结:
此篇博客主要是记录简单的XML文档C#代码操作。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cpp_learners

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值