C#操作Xml的两种方式 XPath XmlDocument XmlNodeList
来源:互联网 发布:鹿晗关晓彤 程序员 编辑:程序博客网 时间:2024/05/01 12:56
现有 XML 文件,内容如下:
<?xml version="1.0" encoding="utf-8" ?><Company> <Department > <Name>IT Department</Name> <Manager>猪头三</Manager> <Employees> <Employee> <ID code="001" >10001</ID> <Name>西门庆</Name> <Gender>男</Gender> </Employee> <Employee> <ID code="002">10202</ID> <Name>潘金莲</Name> <Gender>女</Gender> </Employee> </Employees> </Department></Company>
需要取得 Name 为 “西门庆” 的 Employee 节点,用XPath实现如下:
XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load( Path.Combine( Environment.CurrentDirectory, "demo.xml" ) );XmlNode emp = xmlDoc.SelectSingleNode( "/Company/Department/Employees/Employee[Name='西门庆']" );//emp 即为 定位到的 Employee 节点
需要取得 code 为 002 的 Employee 节点, 用 XPath 实现如下:
XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load( Path.Combine( Environment.CurrentDirectory, "demo.xml" ) );XmlNode emp = xmlDoc.SelectSingleNode( "/Company/Department/Employees/Employee/ID[@code='002']/parent::node()" );
XPath 寻径简介
xml文件,是一种树状结构, XPath 是针对xml文件寻径的一种 pattern。以开头的xml数据为例,下面给出几个常用的情形:
- 取得所有的 Employee
/Company/Department/Employees/Employee
XPath的开头是一个斜线(/)代表绝对路径
- 取得所有的 Name,不分层次
//Name
XPath 以 // 开头表示不限层次的一种模式
- 使用 * 匹配未知名称的元素(不能匹配未知层级)
1. 取得所有的 Employee
/Company/Department/Employees/*
2. 取得Department下,包含有 Employee 作为子节点的节点
/Company/Department/*/Employee
- 使用 [] 选择分支
XPath中的元素索引,是从 1 开始的
我们要选择 第一个 Employee
/Company/Department/Employees/Employee[1]
选择最后一个Employee
/Company/Department/Employees/Employee[last()]
选择叫西门庆的Employee
/Company/Department/Employees/Employee[Name='西门庆']
- 多路选择
XPath 用 | 或者 Or 进行多路选择
/Company/Deparment/Manager | /Company/Deparment/Name
- 选择属性
XPath中的属性,使用@开头
选择所有的 code 属性
本文转自:http://www.cnblogs.com/wequst/archive/2009/01/08/1371769.html
- C#操作Xml的两种方式 XPath XmlDocument XmlNodeList
- C#操作Xml的两种方式 XPath XmlDocument XmlNodeList
- C#操作Xml的两种方式 XPath XmlDocument XmlNodeList
- C#操作Xml的两种方式 XPath XmlDocument XmlNodeList
- C#操作Xml的两种方式 XPath XmlDocument
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- XmlDocument和LINQ to XML两种方式对xml的创建、查询
- vb中利用XmlDocument XmlNode XmlNodeList 解析xml格式的字符串
- C#操作XML的完整例子——XmlDocument篇
- C#操作XML的完整例子——XmlDocument篇
- C#操作XML的完整例子——XmlDocument篇
- C#操作XML的完整例子——XmlDocument篇
- C#操作XML的完整例子——XmlDocument篇
- C#操作XML的完整例子——XmlDocument,LIng
- C# XML文件的一些操作(XmlDocument、XmlElement、XmlNode)
- C#中的多线程
- ORACLE11g 的安装
- 采用struts上传文件
- Photoshop 去掉图片上的文字的几个方法
- CSS实现完美垂直居中[转]
- C#操作Xml的两种方式 XPath XmlDocument XmlNodeList
- 项目管理总结报告》编写指南[转]
- 软件工程师招聘需求
- 项目计划
- 如何成为一个程序员
- 写文档信息
- 测试某url是否被squid 缓存
- 网络字节转换inet_aton & inet_ntoa & inet_addr和inet_pton & inet_ntop
- 面试题链接