当前位置:网站首页>Dom4J解析XML、Xpath检索XML
Dom4J解析XML、Xpath检索XML
2022-07-01 18:43:00 【斯文~】
概述
两种解析方式
1.SAX解析
2.DOM解析
Dom常见的解析工具
DOM解析解析文档对象模型
Dom4J解析XML文件
Dom4J官网: https://dom4j.github.io/
实现步骤
1.下载Dom4j框架;
2.在项目中创建一个文件夹:lib;
3.将dom4j-2.1.1.jar文件复制到 lib 文件夹;
4.在jar文件上点右键,选择 Add as Library -> 点击OK;
5.在类中导包使用;
构造器、方法
Dom4J的解析思想
得到文档对象Document,从中获取元素对象和内容。
SAXReader类
构造器 | 说明 |
---|---|
public SAXReader() | 创建Dom4J的解析器对象 |
Document read(String url) | 加载XML文件成为Document对象 |
Document类
方法 | 说明 |
---|---|
Element getRootElement() | 获得根元素对象 |
List<Element> elements() | 得到当前元素下所有子元素 |
List<Element> elements(String name) | 得到当前元素下指定名字的子元素返回集合 |
Element element(String name) | 得到当前元素下指定名字的子元素,如果有很多名字相同的返回第一个 |
String getName() | 得到元素名字 |
String attributeValue(String name) | 通过属性名直接得到属性值 |
String elementText(子元素名) | 得到指定名称的子元素的文本 |
String getText() | 得到文本 |
代码示例
Dom4JDemo1.java
public class Dom4JDemo1 {
@Test
public void parseXMLData() throws Exception {
// 1、创建一个Dom4j的解析器对象,代表了整个dom4j框架
SAXReader saxReader = new SAXReader();
// 2、把XML文件加载到内存中成为一个Document文档对象
// Document document = saxReader.read(new File("xml-app\\src\\Contacts.xml")); // 需要通过模块名去定位
// Document document = saxReader.read(new FileInputStream("xml-app\\src\\Contacts.xml"));
// 注意: getResourceAsStream中的/是直接去src下寻找的文件
InputStream is = Dom4JDemo1.class.getResourceAsStream("/Contacts.xml");
Document document = saxReader.read(is);
// 3、获取根元素对象
Element root = document.getRootElement();
System.out.println(root.getName());
// 4、拿根元素下的全部子元素对象(一级)
// List<Element> sonEles = root.elements();
List<Element> sonEles = root.elements("contact");
for (Element sonEle : sonEles) {
System.out.println(sonEle.getName());
}
// 拿某个子元素
Element userEle = root.element("user");
System.out.println(userEle.getName());
// 默认提取第一个子元素对象 (Java语言。)
Element contact = root.element("contact");
// 获取子元素文本
System.out.println(contact.elementText("name"));
// 去掉前后空格
System.out.println(contact.elementTextTrim("name"));
// 获取当前元素下的子元素对象
Element email = contact.element("email");
System.out.println(email.getText());
// 去掉前后空格
System.out.println(email.getTextTrim());
// 根据元素获取属性值
Attribute idAttr = contact.attribute("id");
System.out.println(idAttr.getName() + "-->" + idAttr.getValue());
// 直接提取属性值
System.out.println(contact.attributeValue("id"));
System.out.println(contact.attributeValue("vip"));
}
}
Contacts.xml
<?xml version="1.0" encoding="UTF-8"?>
<contactList>
<contact id="1" vip="true">
<name> 潘金莲 </name>
<gender>女</gender>
<email>[email protected]</email>
</contact>
<contact id="2" vip="false">
<name>武松</name>
<gender>男</gender>
<email>[email protected]</email>
</contact>
<contact id="3" vip="false">
<name>武大狼</name>
<gender>男</gender>
<email>[email protected]</email>
</contact>
<user>
</user>
</contactList>
XML检索技术:Xpath
XPath介绍
XPath使用路径表达式来定位XML文档中的元素节点或属性节点,Xpath技术更加适合做信息检索。
使用流程
1.导入jar包(dom4j和jaxen-1.1.2.jar),Xpath技术依赖Dom4j技术;
2.通过dom4j的SAXReader获取Document对象;
3.利用XPath提供的API,结合XPath的语法完成选取XML文档元素节点进行解析操作;
方法 | 说明 |
---|---|
Node selectSingleNode("表达式") | 获取符合表达式的唯一元素 |
List<Node> selectNodes("表达式") | 获取符合表达式的元素集合 |
Xpath的检索方法
1.绝对路径
/根元素/子元素/孙元素
采用绝对路径获取从根节点开始逐层的查找节点列表并返回信息。
从根元素开始,一级一级向下查找,不能跨级。
2.相对路径
./子元素/孙元素
先得到根节点,再采用相对路径获取下一级节点的子节点并返回信息。
从当前元素开始,一级一级向下查找,不能跨级。
3.全文检索
直接全文搜索所有的指定元素并返回。
4.属性查找
在全文中搜索属性,或者带属性的元素。
代码示例
XPathDemo.java
public class XPathDemo {
/** 1.绝对路径: /根元素/子元素/子元素。 */
@Test
public void parse01() throws Exception {
// a、创建解析器对象
SAXReader saxReader = new SAXReader();
// b、把XML加载成Document文档对象
Document document =
saxReader.read(XPathDemo.class.getResourceAsStream("/Contacts2.xml"));
// c、检索全部的名称
List<Node> nameNodes = document.selectNodes("/contactList/contact/name");
for (Node nameNode : nameNodes) {
Element nameEle = (Element) nameNode;
System.out.println(nameEle.getTextTrim());
}
}
/** 2.相对路径: ./子元素/子元素。 (.代表了当前元素) */
@Test
public void parse02() throws Exception {
// a、创建解析器对象
SAXReader saxReader = new SAXReader();
// b、把XML加载成Document文档对象
Document document =
saxReader.read(XPathDemo.class.getResourceAsStream("/Contacts2.xml"));
Element root = document.getRootElement();
// c、检索全部的名称
List<Node> nameNodes = root.selectNodes("./contact/name");
for (Node nameNode : nameNodes) {
Element nameEle = (Element) nameNode;
System.out.println(nameEle.getTextTrim());
}
}
/** 3.全文搜索: //元素 在全文找这个元素 //元素1/元素2 在全文找元素1下面的一级元素2 //元素1//元素2 在全文找元素1下面的全部元素2 */
@Test
public void parse03() throws Exception {
// a、创建解析器对象
SAXReader saxReader = new SAXReader();
// b、把XML加载成Document文档对象
Document document =
saxReader.read(XPathDemo.class.getResourceAsStream("/Contacts2.xml"));
// c、检索数据
//List<Node> nameNodes = document.selectNodes("//name");
// List<Node> nameNodes = document.selectNodes("//contact/name");
List<Node> nameNodes = document.selectNodes("//contact//name");
for (Node nameNode : nameNodes) {
Element nameEle = (Element) nameNode;
System.out.println(nameEle.getTextTrim());
}
}
/** 4.属性查找。 //@属性名称 在全文检索属性对象。 //元素[@属性名称] 在全文检索包含该属性的元素对象。 //元素[@属性名称=值] 在全文检索包含该属性的元素且属性值为该值的元素对象。 */
@Test
public void parse04() throws Exception {
// a、创建解析器对象
SAXReader saxReader = new SAXReader();
// b、把XML加载成Document文档对象
Document document =
saxReader.read(XPathDemo.class.getResourceAsStream("/Contacts2.xml"));
// c、检索数据
List<Node> nodes = document.selectNodes("//@id");
for (Node node : nodes) {
Attribute attr = (Attribute) node;
System.out.println(attr.getName() + "===>" + attr.getValue());
}
// 查询name元素(包含id属性的)
// Node node = document.selectSingleNode("//name[@id]");
Node node = document.selectSingleNode("//name[@id=888]");
Element ele = (Element) node;
System.out.println(ele.getTextTrim());
}
}
Contacts2.xml
<?xml version="1.0" encoding="UTF-8"?>
<contactList>
<contact id="1" vip="true">
<name> 潘金莲 </name>
<gender>女</gender>
<email>[email protected]</email>
</contact>
<contact id="2" vip="false">
<name>武松</name>
<gender>男</gender>
<email>[email protected]</email>
</contact>
<contact id="3" vip="false">
<name>武大狼</name>
<gender>男</gender>
<email>[email protected]</email>
</contact>
<user>
<contact>
<info>
<name id="888">我是西门庆</name>
</info>
</contact>
</user>
</contactList>
边栏推荐
- 如何使用物联网低代码平台进行个人设置?
- 1. "Create your own NFT collections and publish a Web3 application to show them." what is NFT
- Getting started with kubernetes command (namespaces, pods)
- 【快应用】Win7系统使用华为IDE无法运行和调试项目
- 洞态在某互联⽹⾦融科技企业的最佳落地实践
- Appgallery connect scenario development practice - image storage and sharing
- Solution of digital supply chain centralized purchase platform in mechanical equipment industry: optimize resource allocation and realize cost reduction and efficiency increase
- ES6数组方法find()、findIndex()的总结「建议收藏」
- PriorityQueue的用法和底层实现原理
- Viewing the whole ecology of Tiktok from a macro perspective
猜你喜欢
Lumiprobe 自由基分析丨H2DCFDA说明书
How to realize the applet in its own app to realize continuous live broadcast
Prices of Apple products rose across the board in Japan, with iphone13 up 19%
C-end dream is difficult to achieve. What does iFLYTEK rely on to support the goal of 1billion users?
Create your own NFT collections and publish a Web3 application to show them (Introduction)
洞态在某互联⽹⾦融科技企业的最佳落地实践
PMP是被取消了吗??
【快应用】text组件里的文字很多,旁边的div样式会被拉伸如何解决
6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单
SuperOptiMag 超导磁体系统 — SOM、SOM2 系列
随机推荐
VBA simple macro programming of Excel
Manufacturing SRM management system supplier all-round closed-loop management, to achieve procurement sourcing and process efficient collaboration
Getting started with kubernetes command (namespaces, pods)
数据库基础:select基本查询语句
制造业SRM管理系统供应商全方位闭环管理,实现采购寻源与流程高效协同
Lumiprobe phosphide hexaethylene phosphide specification
The former 4A executives engaged in agent operation and won an IPO
实例讲解将Graph Explorer搬上JupyterLab
ES6 summary "suggestions collection" of array methods find(), findindex()
Lean thinking: source, pillar, landing. I understand it after reading this article
Graduation season | Huawei experts teach the interview secret: how to get a high paying offer from a large factory?
有关 M91 快速霍尔测量仪的更多信息
Supervarimag superconducting magnet system SVM series
学习笔记-JDBC连接数据库操作的步骤
How to realize the bottom layer of read-write lock in go question bank 16
生鲜行业B2B电商平台解决方案,提高企业交易流程标准化和透明度
AppGallery Connect场景化开发实战—图片存储分享
Leetcode-128 longest continuous sequence
Three ways for redis to realize current limiting
ETL development of data warehouse (IV)