原创地址: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. 实用的PHP正则表达式

    正则表达式是程序开发中一个重要的元素,它提供用来描述或匹配文本的字符串,如特定的字符.词或算式等.但在某些情况下,用正则表达式去验证一个字符串比较复杂和费时.本文为你介绍10种常见的实用PHP正则表达 ...

  2. linux内核交互,设备驱动控制管理接口

    1,ioctl preface--starting point ,format,mount volume,in addition to the above file system -- allows ...

  3. N1必备外来语

    201412: キャリア: ノルマ:(normal)定额,劳动基本定额. チーフ: コスト: バンド:[英] band;皮带,腰带:吹奏乐团,轻音乐乐团(演奏者の一団.楽団.楽隊):营居群 [2014 ...

  4. Android 自己定义 TextView drawableTop 图标与文字左对齐(效果图)

    public class DrawableTopLeftTextView extends TextView { private Paint mPaint; private float fFontHei ...

  5. BZOJ 3674 可持久化并查集加强版 可持久化并查集

    题目大意:同3673 强制在线 同3673 仅仅只是慢了一些0.0 这道题仅仅写路径压缩比仅仅写启示式合并要快一点点 两个都写就慢的要死0.0 改代码RE的可能是内存不够 #include<cs ...

  6. R-plot

    颜色.图例和线 在散点图中添加信息.图例以及回归线. 模拟数据 #模拟数据 dat <- data.frame(X = runif(100,-2,2),T1 = gl(n=4,k=25,labe ...

  7. win7下安装Ubuntukylin-14.04双系统

    工具准备: 下载ISO系统镜像,UltraISO,EasyBCD,分区助手,8G 优盘 U盘启动制作流程: 1,打开分区助手,从硬盘中分出空闲空间(60G)作为Ubuntu工作空间,文件系统设为Ext ...

  8. Map笔记总结

    Map :存储的是键值对,一对一对出现的,要保证键的唯一性. Map常见的三个子类.1.HashTable 底层是哈希表结构,不能存在null的情况.该集合是线程同步的.效率低此类实现一个哈希表,该哈 ...

  9. C# 用模板生成静态页

    最近在研究静态页输出的问题,找了一些资料.做了一个简单的模板模式的静态输出 模板代码: <html xmlns="http://www.w3.org/1999/xhtml"& ...

  10. c#中的数据类型简介(string)

    Sting 字符串 引入话题 字符串是一个引用类型,从string数据类型的代码定义中也可以看出它实现了IEnumerable<char>接口和IEnumerable接口,因此字符串可以看 ...