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(@*)]");
相关推荐
IT_Octopus12 小时前
一次由 RestTemplate 引发的 Connection reset:被 XML 截胡的请求体
xml·java·spring boot
Dontla12 小时前
网站爬虫控制策略介绍(robots.txt、sitemap.xml、x-robots-tag、noindex、nofollow)网站索引
xml·爬虫·dubbo
风起洛阳@不良使1 天前
spring中xml和注解开发的对比
xml·java·spring
Mikowoo0072 天前
批量汇总XML格式的发票信息
xml·python
逃逸线LOF3 天前
xml文件如何加载properties文件(spring容器加载properties文件)
xml
前网易架构师-高司机5 天前
带标注的山体滑坡塌方数据集数据集,识别率78.1%,974张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·自然灾害·山体滑坡
程序媛kelly5 天前
.xml / .jrxml 文件怎么打开?OpenFiles 实测预览、编辑、搜索与 AI 摘要排查流程
xml·人工智能·jrxml
潘潘的嵌入式日记6 天前
改完Keil工程文件被缓存覆盖?——uvprojx编辑的进阶四坑
xml·嵌入式·keil·调试·mdk·工程文件
Full Stack Developme6 天前
Flowable XML标签大全
xml
C137的本贾尼7 天前
第九篇:微服务与分布式——把一个大系统拆成多个小服务
xml·spring boot·后端