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(@*)]");
相关推荐
2301_8187320620 小时前
项目启动报错,错误指向xml 已解决
xml·java·数据库·后端·springboot
csdn2015_2 天前
generatorConfig.xml 配置 Controller、Service 完整教程
xml·mybatis
特立独行的猫a2 天前
从XML到Compose的UI变革:现代(2026)Android开发指南
android·xml·ui·compose·jetpack
spencer_tseng2 天前
Stream not available [SysDictDataMapper.xml]
xml·java
qq_297574673 天前
MySQL迁移到瀚高数据库 常用转换函数对照表(附XML示例,直接复用)
xml·数据库·mysql
好好研究4 天前
SpringBoot整合SpringMVC
xml·java·spring boot·后端·mvc
从此不归路5 天前
Qt5 进阶【12】JSON/XML 数据协议处理:与后端/配置文件的对接
xml·开发语言·c++·qt·json
方芯半导体6 天前
EtherCAT “通信 + 控制“ 的全国产化控制方案,ESC芯片(FCE1323)与国产MCU芯片功能板解析
xml·网络·单片机·嵌入式硬件·网络协议·机器人·自动化
好好研究6 天前
总结SSM设置欢迎页的方式
xml·java·后端·mvc
R-sz7 天前
mybatis的XML,如何多值匹配,支持单值(=)和多值(IN)查询
xml·mybatis