XML—DOM4J for XML parsing
Why is there Dom4j in the first place?
Because DOM consumes too much memory, and SAX can only read XML, but cannot add, delete, etc. So Dom4j appeared, which is more efficient and can also perform crud operations.
1. Introduction to DOM4J
Dom4j is a simple, flexible open source library. Dom4j was split off from the early developers of JDOM and then developed independently. Unlike JDOM, dom4j uses interfaces and abstract base classes. Although Dom4j's API is relatively complex, it provides better flexibility than JDOM.
Dom4j is a very excellent Java XML API with excellent performance, powerful functions and extremely easy to use. Many software now use Dom4j, such as Hibernate, including Sun's own JAXP, which also uses Dom4j.
To develop using Dom4j, you need to download the corresponding jar file of dom4j and import it into the project. Download address dom4j download
2.DOM4J case
still use our previous XML file:
<?xml version="1.0" encoding="utf-8" standalone="no"?><班级> <学生 地址="香港"> <名字>周小星</名字> <年龄>23</年龄> <介绍>学习刻苦</介绍> </学生> <学生 地址="澳门"> <名字>林晓</名字> <年龄>25</年龄> <介绍>是一个好学生</介绍> </学生></班级>
This document is placed In the com.dom4j.test
package.
Using DOM4J also requires obtaining the Document
object representing the entire document, but this Document object is in the org.dom4j
package.
Obtain the Document object in the main method as follows:
// 1.得到一个解析器SAXReader saxReader = new SAXReader(); // 2.指定解析哪个XML文件Document document = saxReader.read(new File("src/com/dom4j/test/myClass.xml"));
Then we can write the corresponding method according to the needs and call it in the main method.
【1】Specify to read an element (read the first student’s information)
public static void read(Document document) { // 得到根元素 Element root = document.getRootElement(); // root.elements("学生"):表示取出root下的所有学生元素 // root.element("学生"):表示取出root下的第一个学生元素 Element student = root.element("学生"); // 取出属性 String address = student.attributeValue("地址"); // 取出各个子节点的值 String name = student.element("名字").getText(); String age = student.element("年龄").getText(); String intro = student.element("介绍").getText(); System.out.println(address); System.out.println(name); System.out.println(age); System.out.println(intro); }
【2】Add element: Adding student information to the XML document
public static void add(Document document) throws Exception { // 首先我们来创建一个学生节点对象 Element student = DocumentHelper.createElement("学生"); Element name = DocumentHelper.createElement("名字"); name.setText("小强"); Element age = DocumentHelper.createElement("年龄"); age.setText("22"); Element intro = DocumentHelper.createElement("介绍"); intro.setText("是一个三好学生"); // 把三个子元素加到student节点下 student.add(name); student.add(age); student.add(intro); // 为学生添加属性 student.addAttribute("地址", "大理"); // 将学生节点添加到根节点下 document.getRootElement().add(student); // 更新xml文件,直接输出会出现中文乱码,要用OutputFormat OutputFormat output = OutputFormat.createPrettyPrint(); // 设置输出的编码为utf-8 output.setEncoding("utf-8"); // 这里一定要用FileOutputStream字节流输出,不能用FileWriter,否则还会有乱码 XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/dom4j/test/myClass.xml"), output); xmlWriter.write(document); xmlWriter.close(); }
To add students to the XML document, you also need to write the Document object in the memory to the corresponding file at the end, otherwise all operations are only performed in the memory. , and will not be output to a file, which is similar to DOM.
We can still write this updated code as a separate method, as follows:
public static void update(Document document) throws Exception { // 更新xml文件,直接输出会出现中文乱码,要用OutputFormat OutputFormat output = OutputFormat.createPrettyPrint(); // 设置输出的编码为utf-8 output.setEncoding("utf-8"); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/dom4j/test/myClass.xml"), output); xmlWriter.write(document); xmlWriter.close(); }
[3] Add an element to the specified position
public static void addByIndex(Document document) throws Exception { // 创建一个元素 Element newStu = DocumentHelper.createElement("学生"); newStu.setText("王小明"); // 得到所有学生的list List allStudent = document.getRootElement().elements("学生"); allStudent.add(1, newStu); update(document); }
Here, you can actually add it directly to the obtained List
and then update it. The List
here is the List
# in the
java.util package [4] Delete an element or delete this Element attributes
Deleting an element is similar to DOM, in that the node is deleted through the corresponding parent node. For example, we want to delete the first student node:
public static void delete(Document document) throws Exception { // 找到该元素 Element student = document.getRootElement().element("学生"); // 删除元素的某个属性 student.remove(student.attribute("地址")); // 通过父节点删除节点 student.getParent().remove(student); update(document); }
[5] Update element
For example, we want to add 1 to the age of all students, and add 1 to the age of all students. Change the address attribute to United States:
public static void updateAgeAndAddress(Document document) throws Exception { Element root = document.getRootElement(); List<Element> list = root.elements(); for (Element element : list) { // 更新属性 element.addAttribute("地址", "美国"); // 更新年龄子节点的值 Element e_age = element.element("年龄"); int age = Integer.parseInt(e_age.getTextTrim()); e_age.setText(String.valueOf(age + 1)); } update(document); }
Why is there Dom4j in the first place?
Because DOM consumes too much memory, and SAX can only read XML, but cannot add, delete, etc. So Dom4j appeared, which is more efficient and can also perform crud operations.
1. Introduction to DOM4J
Dom4j is a simple, flexible open source library. Dom4j was split off from the early developers of JDOM and then developed independently. Unlike JDOM, dom4j uses interfaces and abstract base classes. Although Dom4j's API is relatively complex, it provides better flexibility than JDOM.
Dom4j is a very excellent Java XML API with excellent performance, powerful functions and extremely easy to use. Many software now use Dom4j, such as Hibernate, including Sun's own JAXP, which also uses Dom4j.
To develop using Dom4j, you need to download the corresponding jar file of dom4j and import it into the project. Download address dom4j download
2.DOM4J case
still use our previous XML file:
<?xml version="1.0" encoding="utf-8" standalone="no"?><班级> <学生 地址="香港"> <名字>周小星</名字> <年龄>23</年龄> <介绍>学习刻苦</介绍> </学生> <学生 地址="澳门"> <名字>林晓</名字> <年龄>25</年龄> <介绍>是一个好学生</介绍> </学生></班级>
The document is placed In the com.dom4j.test
package.
Using DOM4J also requires obtaining the Document
object representing the entire document, but this Document object is in the org.dom4j
package.
Obtain the Document object in the main method as follows:
// 1.得到一个解析器SAXReader saxReader = new SAXReader(); // 2.指定解析哪个XML文件Document document = saxReader.read(new File("src/com/dom4j/test/myClass.xml"));
Then we can write the corresponding method according to the needs and call it in the main method.
【1】Specify to read an element (read the first student’s information)
public static void read(Document document) { // 得到根元素 Element root = document.getRootElement(); // root.elements("学生"):表示取出root下的所有学生元素 // root.element("学生"):表示取出root下的第一个学生元素 Element student = root.element("学生"); // 取出属性 String address = student.attributeValue("地址"); // 取出各个子节点的值 String name = student.element("名字").getText(); String age = student.element("年龄").getText(); String intro = student.element("介绍").getText(); System.out.println(address); System.out.println(name); System.out.println(age); System.out.println(intro); }
【2】Add element: Add a student information to the XML document
public static void add(Document document) throws Exception { // 首先我们来创建一个学生节点对象 Element student = DocumentHelper.createElement("学生"); Element name = DocumentHelper.createElement("名字"); name.setText("小强"); Element age = DocumentHelper.createElement("年龄"); age.setText("22"); Element intro = DocumentHelper.createElement("介绍"); intro.setText("是一个三好学生"); // 把三个子元素加到student节点下 student.add(name); student.add(age); student.add(intro); // 为学生添加属性 student.addAttribute("地址", "大理"); // 将学生节点添加到根节点下 document.getRootElement().add(student); // 更新xml文件,直接输出会出现中文乱码,要用OutputFormat OutputFormat output = OutputFormat.createPrettyPrint(); // 设置输出的编码为utf-8 output.setEncoding("utf-8"); // 这里一定要用FileOutputStream字节流输出,不能用FileWriter,否则还会有乱码 XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/dom4j/test/myClass.xml"), output); xmlWriter.write(document); xmlWriter.close(); }
To add a student to the XML document, you also need to write the Document object in the memory to the corresponding file at the end, otherwise all operations are only performed in the memory. , and will not be output to a file, which is similar to DOM.
We can still write this updated code as a separate method, as follows:
public static void update(Document document) throws Exception { // 更新xml文件,直接输出会出现中文乱码,要用OutputFormat OutputFormat output = OutputFormat.createPrettyPrint(); // 设置输出的编码为utf-8 output.setEncoding("utf-8"); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/dom4j/test/myClass.xml"), output); xmlWriter.write(document); xmlWriter.close(); }
[3] Add an element to the specified position
public static void addByIndex(Document document) throws Exception { // 创建一个元素 Element newStu = DocumentHelper.createElement("学生"); newStu.setText("王小明"); // 得到所有学生的list List allStudent = document.getRootElement().elements("学生"); allStudent.add(1, newStu); update(document); }
Here, you can actually add it directly to the obtained List
and then update it. The List
here is the List
# in the
java.util package [4] Delete an element or delete this Element attributes
Deleting an element is similar to DOM, in that the node is deleted through the corresponding parent node. For example, we want to delete the first student node:
public static void delete(Document document) throws Exception { // 找到该元素 Element student = document.getRootElement().element("学生"); // 删除元素的某个属性 student.remove(student.attribute("地址")); // 通过父节点删除节点 student.getParent().remove(student); update(document); }
[5] Update element
For example, we want to add 1 to the age of all students, and add 1 to the age of all students. Change the address attribute to United States:
public static void updateAgeAndAddress(Document document) throws Exception { Element root = document.getRootElement(); List<Element> list = root.elements(); for (Element element : list) { // 更新属性 element.addAttribute("地址", "美国"); // 更新年龄子节点的值 Element e_age = element.element("年龄"); int age = Integer.parseInt(e_age.getTextTrim()); e_age.setText(String.valueOf(age + 1)); } update(document); }
以上就是XML—XML解析之DOM4J的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Processing and displaying geolocation and map data using PHP and XML Overview: Processing and displaying geolocation and map data is a common requirement when developing web applications. PHP is a popular server-side programming language that can interact with data in XML format. This article explains how to use PHP and XML to process and display geolocation and map data, and provides some sample code. 1. Preparation: Before starting, you need to ensure that PHP and related extensions, such as Simple, are installed on the server
