XML DOM4J 三、XPath

1 什么是XPath

XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。XPath基于XML的树状结构,提供在数据结构树中找寻节点的能力。起初 XPath 的提出的初衷是将其作为一个通用的、介于XPointer与XSL间的语法模型。但是 XPath 很快的被开发者采用来当作小型查询语言。

2 DOM4J对XPath的支持

在DOM4J中,Node接口中的三个方法最为常用:

  1. List selectNodes(String xpathExpression):在当前节点中查找满足XPath表达式的所有子节点;
  2. Node selectSingleNode(String xpathExpression):在当前节点中查找满足XPath表达式的第一个子节点;
  3. String valueOf(String xpathExpression):在当前节点中查找满足XPath表达式的第一个子节点的文本内容;
java 复制代码
Document doc = reader.read(new FileInputStream("person.xml"));
		
		Element root = doc.getRootElement();
		List<Element> eList = root.selectNodes("/persons");
		List<Element> eList1 = root.selectNodes("/persons/person/name");
		
		
		List<Element> eList2 = root.selectNodes("//age");
		List<Element> eList3 = root.selectNodes("//person/age");
		
		
		List<Element> eList4 = root.selectNodes("/*/*/address");
		List<Element> eList5 = root.selectNodes("//*");
		
		List<Element> eList6 = root.selectNodes("/persons/person[1]");
		List<Element> eList7 = root.selectNodes("/persons/person[last()]");
		
		
		List<Element> eList8 = root.selectNodes("//@id");
		List<Element> eList9 = root.selectNodes("//person[@id]");
		List<Element> eList10 = root.selectNodes("//person[@*]");
		List<Element> eList11 = root.selectNodes("//*[not(@*)]");
相关推荐
丑八怪大丑4 天前
XML_Tomcat_HTTP
xml·http·tomcat
largecode5 天前
企业名称能在来电显示吗?号码显示公司名服务打通多终端展示
android·xml·ios·iphone·xcode·webview·phonegap
只可远观6 天前
Android XML命令式和Jetpack Compose声明式UI
android·xml
鹏晨互联7 天前
《深入理解 Compose 中的 matchParentSize 与 fillMaxSize —— 从 XML 到 Compose 的对比解析》
xml
小短腿的代码世界7 天前
Qt SVG渲染管线全解析:从XML解析到像素绘制的完整架构设计与性能优化实战
xml·qt·性能优化
HMS工业网络7 天前
技术干货:EtherCAT设备ESI(XML)文件中的CompleteAccess关键字有什么作用
xml·运维·服务器
鹏晨互联8 天前
【Compose vs XML:边框内外间距的实现对比】
android·xml
鹏晨互联10 天前
Jetpack Compose vs XML:fillMaxSize、fillMaxHeight、fillMaxWidth 全面对比
android·xml
如果'\'真能转义说11 天前
OOXML 文档格式剖析:哈希、ZIP结构与识别
xml·算法·c#·哈希算法