当前位置:网站首页>Parsing XML files using Dom4j
Parsing XML files using Dom4j
2022-07-26 14:36:00 【Pig head trying to move bricks】
Use Dom4j analysis XML file
One 、XML analysis Basic knowledge of
1.1 XML Parse type
XML There are ways of parsing 4 Kind of , Namely :DOM analysis 、SAX analysis 、JDOM analysis 、DOM4j analysis . The first two are basic methods , It's official It's not about the platform The latter two are extension methods , It is developed on the basis of basic methods , Only applicable to java platform .
1、DOM analysis :JDK They all come with them , No need to import the package . The parser is required to convert the whole XML All files are loaded into memory , Generate a Document object .
- advantage : Keep structure between elements 、 Relationship , You can add, delete, modify and query elements
- shortcoming :XML File is too large. , May cause memory overflow
2、SAX analysis : It's faster , More efficient parsing , It is progressive scanning Of , Scan and analyze , And take Event driven approach To carry out specific analysis , Each row parsed will trigger an event .
- advantage : There will be no memory overflow problem, and you can deal with large files
- shortcoming : Intelligent reading , Can't write
1.2 Parser
The parser is to provide specific implementation according to different parsing methods , In order to facilitate developers to parse XML, There are some convenient class libraries .
- dom4j: It's relatively simple XML Parsed class library
- Jsoup: It's powerful DOM Way to resolve the class library , Especially for HTML The parsing of is more convenient
Two 、 Use dom4j analysis XML
2.1 Set up the environment
Create a
mavenproject



Will project's maven Change warehouse to local warehouse 
Join the rely on
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
stay
resourcesCreated in the root directoryuser.xmlfile ,

And in user.xml Add the following to the file
<?xml version="1.0" encoding="UTF-8" ?>
<users>
<user id="10001" country="Chinese" source="Android">
<id>10001</id>
<name>admin</name>
<password>111111</password>
</user>
<user id="10002" country="Chinese" source="ios">
<id>10002</id>
<name>tony</name>
<password>666666</password>
</user>
</users>
2.2 analysis XML file
Introduction to parsing steps
1、 Create parser object
// Create parser object
SAXReader saxReader = new SAXReader();
2、 Use the parser object to read XML Document generation Document object
Document document = saxReader.read(Dom4jParseUserXmlTest.class.getClassLoader().getResource("user.xml"));
3、 according to Document Object acquisition XML The elements of ( Tag information )
//3.1 obtain XML The root node of the file
Element rootElement = document.getRootElement();
System.out.println("user.xml The name of the root node of the file is "+rootElement.getName());
//3.2 obtain XML The child node under the root node of the file
System.out.println(" Get root tag users List of sub tags ");
List<Element> usersSubElementList = rootElement.elements();
for (Element userElement : usersSubElementList) {
//String attributeValue(String name); Get the attribute value of the specified attribute name
System.out.println("users Child of the tag "+userElement.getName());
System.out.println("users Sub tag of tag id The property value is "+userElement.attributeValue("id"));
System.out.println("users Sub tag of tag country Property value "+userElement.attributeValue("country"));
System.out.println("users Sub tag of tag sources Property value "+userElement.attributeValue("source"));
System.out.println("3、 obtain user List of sub tags ");
Create name as
Dom4jParseUserXmlTestClass , And add the following ,Start parsing
package com.li.dom4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.util.List;
/** * @author potential */
public class Dom4jParseUserXmlTest {
public static void main(String[] args) {
//1、 Create parser object
SAXReader saxReader = new SAXReader();
//2、 Use the parser object to read XML Document generation Document object try {
Document document = saxReader.read(Dom4jParseUserXmlTest.class.getClassLoader().getResource("user.xml"));
//3、 according to Document Object acquisition XML Element label information
/** * 1、org.dom4j.Document Common methods * Element getRootElement(); obtain XML The root node of the file * 2、org.dom4j.Element Common methods * String getName(); return * List<Element>elements(); Get the sub tag of the tag */
//3.1 obtain XML The root node of the file
Element rootElement = document.getRootElement();
System.out.println("user.xml The name of the root node of the file is "+rootElement.getName());
//3.2 obtain XML The child node under the root node of the file
System.out.println(" Get root tag users List of sub tags ");
List<Element> usersSubElementList = rootElement.elements();
for (Element userElement : usersSubElementList) {
//String attributeValue(String name); Get the attribute value of the specified attribute name
System.out.println("users Child of the tag "+userElement.getName());
System.out.println("users Sub tag of tag id The property value is "+userElement.attributeValue("id"));
System.out.println("users Sub tag of tag country Property value "+userElement.attributeValue("country"));
System.out.println("users Sub tag of tag sources Property value "+userElement.attributeValue("source"));
System.out.println("3、 obtain user List of sub tags ");
List<Element> userSubElementList = userElement.elements();
for (Element userSubElement : userSubElementList) {
System.out.println("user The sub tag name under the tag is "+userSubElement.getName());
//String getText(); Get the text of the tag
System.out.println("user The text of the sub tag under the tag is "+userSubElement.getText());
}
}
// obtain users The first of the labels user label
Element firstUserElement = rootElement.element("user");
// Get the first one user Sub tags under tags password Text for property
//String elementText(String name); Get the text of the sub label of the specified name
String password = firstUserElement.elementText("password");
System.out.println(" first user Child of the tag password The text of "+password);
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
Operation result display 
2.3 dom4j important API explain
org.dom4j.Document Common methods
| Element getRootElement() | obtain XML The root node of the file |
|---|
org.dom4j.Element Common methods
| String getName() | Return the element name |
|---|---|
| Listelements() | Get the sub tag of the tag |
| String attributeValue(String name) | Get the attribute value of the specified attribute name |
| String getText() | Get the text of the tag |
| String elementText(String name) | Get the text of the sub label of the specified name |
边栏推荐
- Maya imports the model into unity
- 在检测分割中一些轻量级网络模型(自己学习的笔记分享)
- 『云原生』KubeSphere可插拔组件之DevOps系统
- 初识Opencv4.X----图像透视变换
- maya将模型导入到unity
- 作业7.25 排序与查找
- [GYCTF2020]FlaskApp
- sp导出贴图到maya
- Use cpolar to build a commercial website (apply for website security certificate)
- [dry goods] data structure and algorithm principle behind MySQL index
猜你喜欢

Plato farm is expected to further expand its ecosystem through elephant swap

OLAP (business) - transaction analysis (query)

TDengine 助力西门子轻量级数字化解决方案 SIMICAS 简化数据处理流程

~6. CCF 2021-09-1 array derivation

C# Winfrom 常用功能整合

【方差分析】之matlab求解

关于存储芯片的入门基础知识

基于双层主题模型的技术演化分析框架及其应用

C# NanUI 相关功能整合

智能家居行业发展,密切关注边缘计算和小程序容器技术
随机推荐
Redis data operation
【干货】MySQL索引背后的数据结构及算法原理
基于SPO语义三元组的疾病知识发现
融合多自然语言处理任务的中医辅助诊疗方案研究——以糖尿病为例
Annotation and reflection
[ostep] 03 virtualized CPU - restricted direct execution mechanism
Sqldeveloper tools quick start
C # use shift > > and operation and & to judge whether the two binary numbers have changed
Uni app from creation to operation to wechat developer tool
14. Bridge-Based Active Domain Adaptation for Aspect Term Extraction 阅读笔记
winscp传输文件和VNC连接问题
敏捷开发与DevOps的对比
【愚公系列】2022年7月 Go教学课程 017-分支结构之IF
Joint entity and event extraction model based on multi task deep learning
如何评价测试质量?
sp导出贴图到maya
Lingo软件的使用
How to do app upgrade test?
多线程——线程池
Tips for unity transparent channel