C# 操作XML文档 使用XmlDocument类方法
发布时间:2023-06-11 04:21:14
W3C制定了XML DOM标准。很多编程语言中多提供了支持W3C XML DOM标准的API。我在之前的文章中介绍过如何使用Javascript对XML文档进行加载与查询。在本文中,我来介绍一下.Net中的XmlDocument类。它支持并扩展了W3C XML DOM标准。它将整个XML文档都先装载进内存中,然后再对XML文档进行操作,所以如果XML文档内容过大,不建议使用XmlDocument类,因为会消耗过多内存。对于很大的XML文档,可以使用XmlReader类来读取。因为XmlReader使用Steam(流)来读取文件,所以不会对内存造成太大的消耗。下面就来看一下如何使用XmlDocument类。
(一) 加载
加载XML比较常用的有三种方法:
public virtual void Load(string filename);
public virtual void Load(Stream inStream);
public virtual void LoadXml(string xml);
下面代码演示如何使用它们:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("XMLFile1.xml");
Entity retrievedAnnotation = _orgService.Retrieve("annotation"
, new Guid("C1B13C7F-F430-E211-8FA1-984BE1731399"), new ColumnSet(true));
byte[] fileContent = Convert.FromBase64String(retrievedAnnotation["documentbody"].ToString());
MemoryStream ms = new MemoryStream(fileContent);
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.Load(ms);
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
XmlDocument xmlDoc3 = new XmlDocument();
xmlDoc3.LoadXml(str);
(二) 查询
对XML的元素、属性、文本的查询可以使用XPath。具体的定义可以参看w3school。
首先应该了解一下XPath表达式:
表达式 | 描述 |
nodename | 选取此节点的所有子节点。 |
/ | 从根节点选取。 |
// | 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。 |
. | 选取当前节点。 |
.. | 选取当前节点的父节点。 |
@ | 选取属性。 |
我们主要使用两个方法来查询XML文档,SelectNodes(xpath expression)和SelectSingleNode(xpath expression)。
SelectNodes返回一个XmlNodeList对象,也就是所有符合xpath表达式的xml节点都将会被返回,你需要对返回的结果进行遍历。
SelectSingleNode只返回第一个符合xpath表达式的节点,或者返回null。
以下面的XML文件为例,我们进行一些演示:
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer id="01" city="Beijing" country="China" name="Lenovo">
<Contact gender="female" title="Support">Li Li</Contact>
</Customer>
<Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
</Customer>
</Customers>
1. 返回所有Contact节点:
XmlNodeList nodelist = xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
Console.WriteLine(node.OuterXml);
}
输出结果为:
<Contact gender="female" title="Support">Li Li</Contact>
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
2. 返回id为02的customer:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.OuterXml);
输出结果为:
<Customer id="02" city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
</Customer>
3. 返回含有contact名为Li Li的contact:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.OuterXml);
输出结果:
<Contact gender="female" title="Support">Li Li</Contact>
4. 返回含有contact名为 Li Li 的customer。注意和3的区别:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[Contact/text()='Li Li']");
Console.WriteLine(node.OuterXml);
输出结果:
<Customer id="01" city="Beijing" country="China" name="Lenovo">
<Contact gender="female" title="Support">Li Li</Contact>
</Customer>
5. (1) 获取outer xml:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.OuterXml);
(2) 获取 inner xml:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.InnerXml);
(3) 获取 text
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.InnerText);
(4) 获取属性
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.Attributes["gender"].Value);
(三) 创建
以创建以下XML文档为例:
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer id="01" name="Lenovo" country="China" city="Beijing">
<Contact title="Support" gender="female">Li Li</Contact>
</Customer>
</Customers>
var xmlDoc = new XmlDocument();
//Create the xml declaration first
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
//Create the root node and append into doc
var el = xmlDoc.CreateElement("Customers");
xmlDoc.AppendChild(el);
// Customer Lenovo
XmlElement elementCustomer = xmlDoc.CreateElement("Customer");
XmlAttribute attrID = xmlDoc.CreateAttribute("id");
attrID.Value = "01";
elementCustomer.Attributes.Append(attrID);
XmlAttribute cityID = xmlDoc.CreateAttribute("city");
cityID.Value = "Beijing";
elementCustomer.Attributes.Append(cityID);
XmlAttribute attrCountry = xmlDoc.CreateAttribute("country");
attrCountry.Value = "China";
elementCustomer.Attributes.Append(attrCountry);
XmlAttribute nameCountry = xmlDoc.CreateAttribute("name");
nameCountry.Value = "Lenovo";
elementCustomer.Attributes.Append(nameCountry);
el.AppendChild(elementCustomer);
// Contact Li Li
XmlElement elementContact = xmlDoc.CreateElement("Contact");
elementContact.InnerText = "Li Li";
XmlAttribute attrGender = xmlDoc.CreateAttribute("gender");
attrGender.Value = "female";
elementContact.Attributes.Append(attrGender);
XmlAttribute titleGender = xmlDoc.CreateAttribute("title");
titleGender.Value = "Support";
elementContact.Attributes.Append(titleGender);
elementCustomer.AppendChild(elementContact);
xmlDoc.Save("test.xml");
总结: XmlDocument类是.Net API中提供的支持W3C XML DOM标准的类。可以用它来创建和查询XML文档。由于XmlDocument要将XML文档的内容全部装载进内存中,所以对于读取内容过大的XML文档,不适合使用XmlDocument类,而可以使用XmlReader来完成读取。
猜你喜欢
- 1.封装什么是封装,谈谈自己对封装的理解,封装就是将类的信息(比如说类的属性)隐藏在类的内部,不允许外部程序直接访问。此时就要提到一个关键字
- 没人会喜欢空指针异常!有什么方法可以避免它们吗?或许吧。。本文将讨论到以下几种技术1.Optional类型(Java 8中新引入的)2.Ob
- 一、重载(Overload)重载是在一个类里面,方法名字相同,而参数不同。返回类型可以相同也可以不同。每个重载的方法(或者构造函数)都必须有
- 前言最近在改进项目的并发功能,但开发起来磕磕碰碰的。看了好多资料,总算加深了认识。于是打算配合查看源代码,总结并发编程的原理。准备从用得最多
- 使用GroupingSearch对搜索结果进行分组Package org.apache.lucene.search.grouping Des
- 一、是什么当下很多公司都采取前后端分离的开发模式,前端和后端的工作由不同的工程师完成。在这种开发模式下,维持一份及时更新且完整的 Rest
- spring mvc @PathVariable / 带斜杠方式获取遇上这个问题,百度google了一下,抄袭里面的内容,可以实现,在此备忘
- 前言首先,事务这个概念是数据库层面的,Spring只是基于数据库中的事务进行扩展,以及提供了一些能让程序员更新方便操作事务的方式Spring
- 一、返回BufferedImage由于spring mvc不支持返回BufferedImage ,所以增加图片转换器@Configurati
- 首先 下载 jedis.jar包然后再 工程设置里面找到Libraries,点击+。添加下载好的jedis.jar包。点击OK退出即可创建J
- 我们通过学习Java基础知识,让自己正式踏入学习Java语言的行列,这篇博客是用来让我们真正的了解并应用面向对象的思想来实现的。使用简单的J
- 一、背景在上一篇文章中,我们使用Seata整合了SpringBoot,在这篇文章中我们使用Seata整合SpringCloud。同时有了上一
- 概述最近在对之前写的一个 Spring Boot 的视频网站项目做功能完善,需要利用 FFmpeg 实现读取视频信息和自动截图的功能,查阅资
- 本文实例为大家分享了Java流布局图形界面编写代码,供大家参考,具体内容如下package jisuanqi;import java.awt
- 项目结构这个是在网上找的资源,出处记不得了,记录一下。程序的总体结构,很简单的:核心代码代码如下:ArrComparator.java类im
- 建库建表DROP DATABASE IF EXISTS mp;CREATE DATABASE mp DEFAULT CHARACTER SE
- 这篇文章主要介绍了SpringCloud Feign参数问题及解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学
- 简介最近学了java基础后对以前不会写的作业深有感触,想起以前各种在网上找资料找别人的代码参考,所以今天特地写了了简单的基于控制台的学生信息
- 本文实例为大家分享了java代码统计小程序,供大家参考,具体内容如下可以测试每周你的工作量package rexExp;import jav
- 本文实例讲述了Java实现的双向匹配分词算法。分享给大家供大家参考,具体如下:目前比较流行的几大分词算法有:基于字符串匹配的分词方法、基于理