当前位置:网站首页>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>
边栏推荐
- 太爱速M源码搭建,巅峰小店APP溢价寄卖源码分享
- Getting started with kubernetes command (namespaces, pods)
- 11、用户、组和权限(1)
- Solution: you can ping others, but others can't ping me
- Lumiprobe phosphide hexaethylene phosphide specification
- Lake Shore - crx-em-hf low temperature probe station
- 透过华为军团看科技之变(六):智慧公路
- Viewing technological changes through Huawei Corps (VI): smart highway
- CDGA|从事通信行业,那你应该考个数据管理证书
- Leetcode-83 delete duplicate elements in the sorting linked list
猜你喜欢
![[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched](/img/5c/b0030fd5fbc07eb94013f2699c2a04.png)
[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched

Leetcode203 remove linked list elements

Summary of the core steps in the life cycle of beans

Cdga | if you are engaged in the communication industry, you should get a data management certificate

Supervarimag superconducting magnet system SVM series

中英说明书丨人可溶性晚期糖基化终末产物受体(sRAGE)Elisa试剂盒

Lake shore optimag superconducting magnet system om series

ACM mm 2022 video understanding challenge video classification track champion autox team technology sharing

网易游戏,激进出海

Lake Shore低温恒温器的氦气传输线
随机推荐
3. "Create your own NFT collections and publish a Web3 application to show them" cast NFT locally
Manufacturing SRM management system supplier all-round closed-loop management, to achieve procurement sourcing and process efficient collaboration
Today, with the popularity of micro services, how does service mesh exist?
6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单
Huawei cloud experts explain the new features of gaussdb (for MySQL)
Games202 operation 0 - environment building process & solving problems encountered
[6.24-7.1] review of wonderful technical blog posts in the writing community
前4A高管搞代运营,拿下一个IPO
Chinese and English instructions human soluble advanced glycation end products receptor (sRAGE) ELISA Kit
Three. JS learning - basic operation of camera (learn from)
How to operate technology related we media well?
【快应用】text组件里的文字很多,旁边的div样式会被拉伸如何解决
宝,运维100+服务器很头疼怎么办?用行云管家!
华为云专家详解GaussDB(for MySQL)新特性
AI training speed breaks Moore's law; Song shuran's team won the RSS 2022 Best Paper Award
Netease games, radical going to sea
JS find the next adjacent element of the number in the array
【pytorch记录】模型的分布式训练DataParallel、DistributedDataParallel
助力数字经济发展,夯实数字人才底座—数字人才大赛在昆成功举办
Huawei game failed to initialize init with error code 907135000