c# xml操作

C下使用XmlDocument操作XML详解

XML(可扩展标记语言)是一种用于存储和传输数据的标记语言,在C中,我们可以使用XmlDocument类来操作XML文档,XmlDocument是一个表示XML文档的DOM(文档对象模型)树的对象,它提供了一组方法来创建、修改和查询XML文档,下面将详细介绍如何使用XmlDocument操作XML文档。

c# xml操作

创建XmlDocument对象

要使用XmlDocument操作XML文档,首先需要创建一个XmlDocument对象,可以通过以下几种方式创建XmlDocument对象:

1、从文件中加载XML文档:

string xmlFilePath = "example.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);

2、从字符串中加载XML文档:

c# xml操作

string xmlString = @"<books>
                        <book>
                            <title>Book1</title>
                            <author>Author1</author>
                        </book>
                        <book>
                            <title>Book2</title>
                            <author>Author2</author>
                        </book>
                    </books>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);

3、从命名空间和XPath加载XML文档:

string xmlNamespace = "http://www.w3.org/2000/xmlns/";
string xmlXPath = "/books";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlNamespace, xmlXPath);

读取XML文档内容

通过XmlNode属性可以访问XML文档中的元素和属性,要获取根元素的所有子元素,可以使用以下代码:

XmlNodeList childNodes = xmlDoc.DocumentElement.ChildNodes;
foreach (XmlNode childNode in childNodes)
{
    Console.WriteLine("节点名称:" + childNode.Name);
}

添加和删除元素和属性

1、添加元素:

c# xml操作

XmlElement newElement = xmlDoc.CreateElement("book");
newElement.SetAttribute("title", "New Book");
newElement.SetAttribute("author", "New Author");
xmlDoc.DocumentElement.AppendChild(newElement);

2、删除元素:

XmlNode deleteNode = xmlDoc.SelectSingleNode("/books/book[@title='New Book']"); // 根据条件选择要删除的节点
if (deleteNode != null)
{
    xmlDoc.DocumentElement.RemoveChild(deleteNode); // 删除选中的节点
}

修改元素和属性值

XmlNode updateNode = xmlDoc.SelectSingleNode("/books/book[@title='New Book']"); // 根据条件选择要更新的节点
if (updateNode != null)
{
    updateNode.InnerText = "Updated Book"; // 修改选中节点的内容或属性值
}

查询XML文档内容(XPath表达式)

string bookTitle = xmlDoc.SelectSingleNode("/books/book[@title='Book1']").InnerText; // 根据XPath表达式查询节点内容并赋值给变量bookTitle
Console.WriteLine("Book Title: " + bookTitle); // 输出查询结果

原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/229847.html

(0)
K-seoK-seoSEO优化员
上一篇 2024年1月19日 07:04
下一篇 2024年1月19日 07:04

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

免备案 高防CDN 无视CC/DDOS攻击 限时秒杀,10元即可体验  (专业解决各类攻击)>>点击进入