XML parsing -- using dom4j open source library

Article directory

1, How to parse XML with dom4j

Dom4j is a simple and flexible open source library. Dom4j was developed independently after being separated by the early developers of JDOM. Unlike JDOM, Dom4j uses interfaces and abstract parent classes. Although the API of Dom4j is relatively complex, it provides better flexibility than JDOM.

Dom4j is a very good Java XML API. Now many software uses Dom4j, such as Hibernate, including sun's own JAXM.

To develop with Dom4j, we need to introduce the corresponding jar file of Dom4j.

Advantages: excellent performance, powerful function, easy to use.
Disadvantages: I don't know yet, but more and more Java software is using dom4j to read and write XML.

2, The steps of dom4j parsing XML

Preparations for parsing XML with Sax:

1. After introducing the three jar packages of dom4j, add environment dependency.

2. Encapsulate the XML file into an object

(1) Create the SaxReader parser object directly

	SAXReader reader = new SAXReader();

(2) Get Document object

	Document doc = reader.read(new File("src/com/empList.xml"));

3, dom4j parsing XML instance

(1) Give the file of XML to be parsed

<?xml version="1.0" encoding="UTF-8"?>
<list>
	<emp id="1">
		<name>Zhang San</name>
		<age>34</age>
		<gender>male</gender>
		<salary>3000</salary>
	</emp>
	<emp id="2">
		<name>Wang Wu</name>
		<age>18</age>
		<gender>female</gender>
		<salary>6500</salary>
	</emp>
	<emp id="3">
		<name>Zhao Liu</name>
		<age>28</age>
		<gender>male</gender>
		<salary>4400</salary>
	</emp>
	<emp id="4">
		<name>Money seven</name>
		<age>19</age>
		<gender>male</gender>
		<salary>12000</salary>
	</emp>
</list>

(2) Encapsulating XML files as Java objects

package com.entity;
/**
 * Class description:
 * 		Encapsulate the emlListXML as an Emp object
 * @author qianliangguo
 */
public class Emp {
	private int id;
	private String name;
	private int age;
	private String gender;
	private double salary;
	public Emp() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Emp(int id, String name, int age, String gender, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.salary = salary;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Emp [id=" + id + ", name=" + name + ", age=" + age
				+ ", gender=" + gender + ", salary=" + salary + "]";
	}
}

(3) Parsing XML with dom4j

Querying nodes in an XML file

package com.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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

import com.entity.Emp;

/**
 * Class description:
 * 		Parsing XML with dom4j
 * Preparation for parsing XML with dom4j:
 * 		1.After introducing three jar packages of dom4j, add environment dependency
 * 		2.Encapsulating XML as a Java object
 * To use dom4j:
 * 		1.Create the SaxReader parser object directly
 * 		2.Get Document object
 * 
 * @author qianliangguo
 */
public class Dom4jXML {
	public static void main(String[] args) throws Exception {
		//1. Create a SaxReader parser
		SAXReader reader = new SAXReader();
		//2. Get Document object
		Document doc = reader.read(new File("src/com/empList.xml"));
		
		/**
		 * Print all attributes and values after XML is encapsulated as an object
		 */
			//Get root node
			Element root = doc.getRootElement();
			//Get all child nodes under the root node
			List<Element> elements = root.elements();
			//Create list < EMP > Save employee information
			List<Emp> list = new ArrayList<Emp>();
			//Traverse child nodes
			for (Element element : elements) {
				//Get the attribute of the node first and then the value of the node
//				String id = element.attribute("id").getValue();
				//Get node values directly from node attributes
				String id = element.attributeValue("id");
				//Get node first and then node value
				String name = element.element("name").getText();
				//Get node value directly from node name
				String age = element.elementText("age");
				String gender = element.elementText("gender");
				String salary = element.elementText("salary");
				Emp emp = new Emp(Integer.parseInt(id),name,Integer.parseInt(age),gender,Double.parseDouble(salary));
				list.add(emp);
			}
			System.out.println(list);
	}
}

Analysis effect:

Add nodes to XML file

Create documents, add elements and nodes (node is the next level of elements specified here)
Add attribute for element: addAttribute(,)
Add child node: addElement()
Add text value: addText()
Add child nodes and set the text addElement().addText()

	/**
	 * Test instructions:
	 * 		Add node to XML file
	 * 
	 * Some API s used:
	 * 		Add attribute for element: addAttribute(,)
	 * 		Add child node: addElement()
	 * 		Add text value: addText()
	 * 		Add child nodes and set the text addElement().addText()
	 * (The next level of element specified here is node)
	 */
	@Test
	public void testAdd() throws Exception{
		//list store Emp objects
		List<Emp> emps = new ArrayList<Emp>();
		emps.add(new Emp(1,"Hudie",21,"male",9000.0));
		emps.add(new Emp(2,"Huahua",20,"female",8000.0));
		emps.add(new Emp(2,"Winter rain",18,"female",10000.0));
		//Create document object
		Document doc = DocumentHelper.createDocument();
		//Create root node
		Element root = doc.addElement("list");
		for (Emp emp : emps) {
			//Add a child element named emp to the root node
			Element ele = root.addElement("emp");
			//Add id attribute for emp element
			ele.addAttribute("id", String.valueOf(emp.getId()));
			//Add a child node and set the text value in the node
			ele.addElement("name").addText(emp.getName());
			ele.addElement("age").addText(String.valueOf(emp.getAge()));
			ele.addElement("gender").addText(emp.getGender());
			ele.addElement("salary").addText(String.valueOf(emp.getSalary()));
		}
		//Create an output stream indicating the output path
		FileOutputStream fos = new FileOutputStream("src/com/EmpList2.xml");
		XMLWriter writer = new XMLWriter();
		writer.setOutputStream(fos);
		//Write out the document to the specified path
		writer.write(doc);
		writer.close();
	}

The test successfully generated an XML file

Modify nodes of XML file

	/**
	 * Test instructions:
	 * 		Delete elements from XML file
	 * @throws Exception
	 */
	@Test
	public void testRemo() throws Exception{
		SAXReader saxReader = new SAXReader();
		Document doc = saxReader.read("src/com/EmpList2.xml");
		//Get root node
		Element root = doc.getRootElement();
		//Get node with subscript 0
		Element element = (Element)root.elements().get(0);
			System.out.println(element.attribute("id"));
		//Delete the id attribute of this node
		element.remove(element.attribute("id"));
			System.out.println(element.attribute("id"));
			
		//Get a node named name
		Element name = element.element("name");
			System.out.println(name.getText());
		//Delete this node
		element.remove(name);
			System.out.println(element.elementText("name"));
	}

Analysis effect:

Deleting attributes and nodes in an XML document

	/**
	 * Test instructions:
	 * 		Modifying nodes and properties in XML documents
	 * @throws Exception
	 */
	@Test
	public void testUpdate() throws Exception{
		//1. Directly create the SaxReader parser object
		SAXReader sax = new SAXReader();
		//2. Get Document object
		Document doc = sax.read("src/com/EmpList2.xml");
		
		//Get root node
		Element root = doc.getRootElement();
		//Get the first node
		Element element = (Element)root.elements().get(0);
		Attribute id = element.attribute("id");
			System.out.println("Of the first node id yes:"+id.getValue());
		//Modify property value
		id.setValue("19");
			System.out.println("After the first node is modified id yes:"+id.getValue());
		//Get name node
		Element name = element.element("name");
			System.out.println("name The value is"+name.getText());
		//Modify the text value of name
		name.setText("Huahudiediedie");
			System.out.println("After modification name The value is"+name.getText());
	}

Analysis effect:

333 original articles published, 871 praised, 130000 visitors+
Private letter follow

Tags: xml Attribute Java Hibernate

Posted on Wed, 15 Jan 2020 01:51:14 -0800 by MytHunter