发布时间:2026-09-28 17:15:01 浏览次数:1
下面是“C#下使用XmlDocument操作XML详解”的完整攻略:
XmlDocument类是C#中处理XML文档的核心类,使用XmlDocument可以实现创建、读取和修改XML文件的功能。创建XmlDocument对象的代码如下:
using System.Xml;XmlDocument xmlDoc = new XmlDocument();在使用XmlDocument读取或者修改XML文件之前,需要先将XML文件加载到XmlDocument对象中。XmlDocument提供了两种方式来加载XML文件,一种是通过Load方法加载本地的XML文件,一种是通过LoadXml方法加载XML字符串。
xmlDoc.Load("example.xml");string xmlString = "<root><item>item1</item><item>item2</item></root>";xmlDoc.LoadXml(xmlString);在XmlDocument对象中通过DocumentElement属性获取根节点对象。
XmlElement root = xmlDoc.DocumentElement;XmlDocument提供了一系列方法,可以获取XML文档中的各种节点。
XmlNodeList nodes = xmlDoc.GetElementsByTagName("item");XmlNodeList nodes = xmlDoc.SelectNodes("//item");XmlDocument提供了CreateElement方法,可以创建XML节点。
XmlElement newNode = xmlDoc.CreateElement("newNode");XmlDocument提供了AppendChild方法,可以将新创建的XML节点添加到XML文档中。
XmlNode rootNode = xmlDoc.SelectSingleNode("//root");rootNode.AppendChild(newNode);下面是两条示例说明:
假设有以下的XML文件example.xml:
<?xml version="1.0" encoding="UTF-8"?><root> <item>item1</item> <item>item2</item></root>我们可以使用XmlDocument来向XML文件中添加一个新节点,代码如下:
using System.Xml;XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("example.xml");XmlElement newNode = xmlDoc.CreateElement("newItem");newNode.InnerText = "item3";XmlNode rootNode = xmlDoc.SelectSingleNode("//root");rootNode.AppendChild(newNode);xmlDoc.Save("example.xml");执行这个程序后,example.xml文件的内容将变为:
<?xml version="1.0" encoding="utf-8"?><root> <item>item1</item> <item>item2</item> <newItem>item3</newItem></root>我们可以使用XmlDocument来删除XML文件中的指定节点。假设有以下的XML文件example.xml:
<?xml version="1.0" encoding="UTF-8"?><root> <item>item1</item> <item>item2</item> <newItem>item3</newItem></root>下面的代码将删除XML文件example.xml中名称为“newItem”的节点:
using System.Xml;XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("example.xml");XmlNode node = xmlDoc.SelectSingleNode("//newItem");XmlNode parentNode = node.ParentNode;parentNode.RemoveChild(node);xmlDoc.Save("example.xml");执行这个程序后,example.xml文件的内容将变为:
<?xml version="1.0" encoding="utf-8"?><root> <item>item1</item> <item>item2</item></root>