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来完成读取。


猜你喜欢
- Viewpager 横向滑动效果系统就自带了很多种,比如这个效果 那如果做成竖屏的这种效果呢 。我百度过很多,效果都不是很好,有的代码特别多
- 本文实例讲述了Java Socket实现多线程通信功能的方法。分享给大家供大家参考,具体如下:前面的文章《Java Socket实现单线程通
- 有时您可能想限制可以在参数化类型中用作类型参数的类型。 例如,对数字进行操作的方法可能只希望接受Number或其子类的实例。 这就是有界类型
- 首先我们看一下hibernate的主配置文件<!DOCTYPE hibernate-configuration PUBLIC &nbs
- 功能描述上传照片文件名及是系统要识别标签或是照片的名称(人物标识)提取照片脸部特征值(调用 facemesh模型)保存特征值添加样本(调用
- Android 自定义imageview实现图片缩放实例详解 觉得这个自定义的imageview很好用 性能不错 所以
- 协程属于Kotlin中非常有特色的一项技术,因为大部分编程语言中是没有协程这个概念的。那么什么是协程呢?它其实和线程有点相似,可以简单地将它
- 可以使用 Intent.createChooser() 的方法来创建 Intent,并传入想要的 Sting 作为标题。 以wallpape
- 介绍环境配置Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEcl
- 现象正常情况下修改完代码,运行项目就会立即生效的。但是突然有一天发现运行的还是老的代码,新代码根本没有生效。通过 mvn clean、 in
- 本文实例讲述了C#自适应合并文件的方法。分享给大家供大家参考。具体实现方法如下:using System;using System.IO;n
- 一、之前旧的写法class Singleton{ private Singleton() {} &nb
- 前言很多时候,当你以为掌握了事实真相的时间,如果你能再深入一点,你可能会发现另外一些真相。比如面向切面编程的最佳编程实践是AOP,AOP的主
- 流,就是一系列的数据。当不同介质之间有数据交互的时候,JAVA就使用流来实现。数据源可以是文件,还可以是数据库、网络甚至其他的程序。比如读取
- 在Android中因为不同像素手机的多样化,对于一张图片,放大不同的手机上因像素不同显示上也会有区别。现有如下需求:将一张图片宽度充满整个屏
- 今天有同事用swagger2开发时,有一方法返回Map<String,List<Object>>出现无法解析错误。P
- Java BorderLayout布局管理器的两种排列java中Frame类默认的布局管理器为BorderLayout,其主要是将Frame
- 这篇文章主要介绍了如何使用java修改文件所有者及其权限,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 一、题目描述二、思路语法基础:StringBuilder 类似列表,可以更改元素。package Practice;public class
- 一、基本概念:线程、进程1.1、进程与线程的具体介绍线程(thread),进程可进一步细化为线程,是一个程序内部的一条执行路径。若一个进程同