原创地址:http://www.cnblogs.com/jfzhu/archive/2012/11/19/2778098.html

转载请注明出处

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 = "";
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");

(四) 更改

还以下面的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 Li Li更改为Evi

XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
node.InnerText = "Evi";

2. 将id为02的Customer的city属性更改为Den Haag

XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
node.Attributes["city"].Value = "Den Haag";

3. 将id为02的Customer的所有下属Contact的title属性更改为Functional Consultant

XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
XmlNodeList nodelist = node.SelectNodes("./Contact");
foreach (XmlNode n in nodelist)
{
n.Attributes["title"].Value = "Functional Consultant";
}

(五) 删除节点

还是以这个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 Li Li节点

XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
node.ParentNode.RemoveChild(node);

结果:

<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer id="01" city="Beijing" country="China" name="Lenovo">
</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>

(六) Namespace

XML文档中如果使用了命名空间该如何进行查询,以下面的文档为例:

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>

查找第一个f:name节点

var names = new XmlNamespaceManager(xmlDoc.NameTable);
names.AddNamespace("h", "http://www.w3.org/TR/html4/");
names.AddNamespace("f", "http://www.w3schools.com/furniture");
XmlNode node = xmlDoc.SelectSingleNode("/root/f:table/f:name", names);
Console.WriteLine(node.InnerText);

总结: XmlDocument类是.Net API中提供的支持W3C XML DOM标准的类。可以用它来创建和查询XML文档。由于XmlDocument要将XML文档的内容全部装载进内存中,所以对于读取内容过大的XML文档,不适合使用XmlDocument类,而可以使用XmlReader来完成读取。

C# 使用XmlDocument类对XML文档进行操作的更多相关文章

  1. XML 文档解析操作

    sing System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security; ...

  2. 通过XmlDocument读写Xml文档参考地址

    /// <summary> /// 获取一个报表的参数 http://blog.csdn.net/hdhai9451/article/details/12170069 /// </s ...

  3. C# 操作XML文档 使用XmlDocument类方法

    W3C制定了XML DOM标准.很多编程语言中多提供了支持W3C XML DOM标准的API.我在之前的文章中介绍过如何使用Javascript对XML文档进行加载与查询.在本文中,我来介绍一下.Ne ...

  4. C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)

    XML文档是一种通用的文档,这种文档既可以用.config作为后缀也可以用.xml作为后缀.XML文档主要由元素节点和节点的属性共同构成的.它有且仅有一个根节点,其他的节点全部都是根节点的子节点或者子 ...

  5. XPath操作XML文档

    NET框架下的Sytem.Xml.XPath命名空间提供了一系列的类,允许应用XPath数据模式查询和展示XML文档数据. 3.1XPath介绍 主要的目的是在xml1.0和1.1文档节点树种定位节点 ...

  6. 文档对象模型操作xml文档

    简介 :文档对象模型(DOM)是一种用于处理xml文档的API函数集. 2.1文档对象模型概述 按照W3C的定义,DOM是“一种允许程序或脚本动态地访问更新文档内容,结构和样式的.独立于平台和语言的规 ...

  7. XML文档

    XML(Extensible Markuo Language)可标记扩展语言.它是一种以简单文本格式存储数据的方式,可以被任何计算机读取. XML文档里包含的元素都是可以自定义的. 1.XML文档声明 ...

  8. 【JAVA与DOM4J实现对XML文档的CRUD操作】

    一.简介 1.网上下载DOM4J 1.6.1压缩包,解压开之后,发现几个目录和一个jar文件,jar文件是必须的文件其它目录: docs目录:帮助文档的目录,单击index.html: Quick s ...

  9. XML文档读取-DOM

    DOM(Document Object Model),“文档对象模型”早期是为了解决不用浏览器间数据兼容问题提出的解决方案,现在已经是W3C组织推荐的处理可扩展标志语言的标准编程接口. W3C DOM ...

随机推荐

  1. 关于Thread的Runnable和Callable接口

    其实非常简单:其实他们的区别就是Callable有返回值并且可以抛出异常. /** * Represents a command that can be executed. Often used to ...

  2. javascript 事件设计模式

    http://plkong.iteye.com/blog/213543 1. 事件设计概述 事件机制可以是程序逻辑更加清晰可见,在JavaScript中很多对象都有自己的事件,如:button有onc ...

  3. Inno Setup 系统托盘图标插件 TrayIconCtrl V1.5

    原文 http://restools.hanzify.org/article.asp?id=93 V1.5 修正在某些 Windows 平台上(例如 Windows XP SP3)不能正常运行的问题. ...

  4. C++类对应的内存结构

    提示1:对“内存结构”表示有疑问或不解的,先参考: http://blog.csdn.net/guogangj/archive/2007/05/25/1625199.aspx, 本文使用的表示方法和V ...

  5. JIRA官方:为什么要用JIRA?

    因为你有各种事务 工作中总是有各种事务要去处理,而这些事务不仅仅是代码中的Bug.这些事务充斥在你的收件箱中,各种想法散落在 Excel表格里,需求隐藏在原有的业务系统中.使用JIRA可以轻松捕捉和管 ...

  6. EasyUI选项卡tab页面处理示例

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  7. linux命令之uname

    uname是linux中查询系统基本信息的命令. 命令形式: uname [选项] 选项包括:(若不跟任何选项:则默认-s选项) -s, --kernel-name 输出内核名称   -n, --no ...

  8. hdu 5607 graph (矩阵乘法快速幂)

    考虑一个经典的问题: 询问从某个点出发,走 k 步到达其它各点的方案数? 这个问题可以转化为矩阵相乘,所以矩阵快速幂即可解决. 本题思路: 矩阵经典问题:求从i点走k步后到达j点的方案数(mod p) ...

  9. EK中fromCharCode和parseInt的配合使用

    基于web的漏洞攻击的第一步一般是:在landing page中通过<script>标签下的JavaScript脚本引入一些恶意链接.这些脚本往往会採用各种各样的混淆.加密手法来躲避AV和 ...

  10. C# 后台调用script使用类

    在网站的开发的时候,总是会用到一些前台的提示的script的代码,从项目中整理了一份常用的方法. public class Jscript { public Jscript() { // // TOD ...