DOM model and Dom4j

DOM document object model

DOM ( D ocument O bject M Odel) and defines the access operation of an XML document standard methods, as XML documents DOM tree view, it is possible to read and write the number of all elements in the DOM.

XML document and its tree structure:

 Dom4j

Dom4j is an easy-to-use open source library for parsing XML. Applied to Java, it has the characteristics of excellent performance, powerful function and easy to use. Dom4j regards XML as Document object, and XML tag is defined as ELement object by Dom4j.

Dom4j traverse XML

Use java's Dom4j package for XML traversal, we download the Dom4j package (click on the URL ), download our own jdk version and select the corresponding Dom4j version, here we choose the version corresponding to java8+

Import it into the java project, right click dom4j.jar after importing and select bulid path->add to build path

Then you can see that the package appears in the reference libriaries, indicating that the package has been imported into the project

The following is an example of simply using Dom4j for XML file operations

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hr SYSTEM "hr.dtd">
<!-- 人力资源管理系统 -->
<hr>
	<employee no="3309">
		<name>张三</name>
		<age>32</age>
		<salary>9200</salary>
		<department>
			<name>会计部</name>
			<addr>XX大厦</addr>
		</department>
	</employee>
		<employee no="3329">
		<name>李四</name>
		<age>32</age>
		<salary>9200</salary>
		<department>
			<name>会计部</name>
			<addr>XX大厦</addr>
		</department>
	</employee>
</hr>

Corresponding Dom4j

package dom4j;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class HrReader {
	public void readXml() {
		String file = "................"; //xml文件路径
		// SAXReader类是读取XML文件的核心类
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			Element root = document.getRootElement();
			List<Element> employees = root.elements("employee");
			for (Element employee : employees) {
				System.out.println(employee.elementText("name"));
				System.out.println(employee.attribute("no").getText());
				System.out.println(employee.elementText("age"));
				System.out.println(employee.elementText("salary"));
				Element department = employee.element("department");
				System.out.println(department.elementText("name"));
				System.out.println(department.elementText("addr"));
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		HrReader reader = new HrReader();
		reader.readXml();
	}

}

The console output is:

张三
330932
9200
会计部
XX大厦
李四
332932
9200
会计部
XX大厦

Dom4j has many other functions, see Dom4j api for details

Guess you like

Origin blog.csdn.net/qq_41459262/article/details/110754144