Table of Contents
XMLProgramming-DOM4J" >XMLProgramming-DOM4J
Parse the text in the form of XML, and get the document Object" >2.Parse the text in the form of XML, and get the document Object
Active creationdocumentObject" >3.Active creationdocumentObject
Node object
, get the root node of the document" >1, get the root node of the document
, get the child nodes of a node" >2, get the child nodes of a node
, get the content of the node " >3, get the content of the node
, get all the names under a node named "member" child nodes, and traverse " >4, get all the names under a node named "member" child nodes, and traverse
, traverse all child nodes under a certain node" >5, traverse all child nodes under a certain node
, add sub-node under a node" >6, add sub-node under a node
, set node text " >7, set node text
, delete A certain node " >8, delete A certain node
, add a CDATA node" >9, add a CDATA node
Node object attributes
, get an attribute under a certain node" >1, get an attribute under a certain node
, get the text of the attribute" >2, get the text of the attribute
, delete an attribute" >3, delete an attribute
, traverse all attributes of a node " >4, traverse all attributes of a node
, Set the attributes and text of a node" >5, Set the attributes and text of a node
, Set the text of the attribute" >6, Set the text of the attribute
Insert a node at the specified position
file" >XML file
" >, If the document is in English
、如果文档含有中文" >2、如果文档含有中文
综合案例
Home Backend Development XML/RSS Tutorial XML Programming-DOM4J

XML Programming-DOM4J

Feb 20, 2017 pm 03:13 PM

XMLProgramming-DOM4J

##Basic Overview


dom4j

is a JavaXML API , similar to jdom, used to read and write XML files. dom4j is a very excellent JavaXML API, which has the characteristics of excellent performance, powerful functions and extremely easy to use. It is also a Open source software, you can find it at SourceForge. You can also find an article on IBM developerWorks on the performance, functionality and ease of use of the mainstream Java XML API reviews, so you can know that dom4j is excellent in every aspect. Nowadays you can see that more and more Java software are using dom4j to read and write XML, it is particularly worth mentioning that even Sun#JAXM is also using dom4j . This is already a must-use jar package, Hibernate also uses it to read and write configuration files.

PSDOM4JOne of the reasons why it is so powerful is that it supports XPath Technology, DOM4J also has corresponding reference documents, you can search and download them if you need them.

Why is there

DOM4J?

Before, the two technologies described in the blog,

DOM and SAX technology, the disadvantage of the former is that it is time consuming Memory, the disadvantage of the latter is that it can only perform read operations, while DOM4J can both submit efficiency and perform crud operations .

PS: To use DOM4J, you need to import the corresponding basic JAR package, If you use the extension function of DOM4J, you also need to import the extension JAR package.

DOM4JGetting started

DOM4JThree ways to obtain Document objects

1.ReadXMLfile,obtaindocumentobject(commonly used)

    SAXReader reader = new SAXReader();
    Document   document = reader.read(new File(“src/input.xml"));
Copy after login

2.Parse the text in the form of XML, and get the document Object

    String text = "<members></members>";
    Document document = DocumentHelper.parseText(text);
Copy after login

3.Active creationdocumentObject

    Document document = DocumentHelper.createDocument();
    //创建根节点
    Element root = document.addElement("members");
Copy after login

PS: Be careful to import the corresponding JAR package.



Node object

1, get the root node of the document

    Element root = document.getRootElement();
Copy after login



2, get the child nodes of a node



    Element element=node.element(“书名");
Copy after login

3, get the content of the node

    String text1=node.getText();
    String text2=node.getTextTrim();	// 去掉内容前面和后面的空格
Copy after login

4, get all the names under a node named "member" child nodes, and traverse

    List nodes = rootElm.elements("member");
    for (Iterator it = nodes.iterator(); it.hasNext();) {
          Element elm = (Element) it.next();
          // do something
    }
Copy after login

5, traverse all child nodes under a certain node

    for(Iterator it=root.elementIterator();it.hasNext();){
        Element element = (Element) it.next();
           // do something
      }
Copy after login

6, add sub-node under a node

    Element ageElm = newMemberElm.addElement("age");
Copy after login

7, set node text

    element.setText("29");
Copy after login

8, delete A certain node

    //childElm是待删除的节点,parentElm是其父节点
    parentElm.remove(childElm);
Copy after login

9, add a CDATA node

    Element contentElm = infoElm.addElement("content");
    contentElm.addCDATA(diary.getContent());
Copy after login


PS: Note that nodes cannot be accessed across layers.


Node object attributes

1, get an attribute under a certain node

    Element root=document.getRootElement();    
      //属性名name
    Attribute attribute=root.attribute("size");
Copy after login

2, get the text of the attribute

     String text=attribute.getText();
Copy after login

3, delete an attribute

    Attribute attribute=root.attribute("size");
    root.remove(attribute);
Copy after login

4, traverse all attributes of a node

     Element root=document.getRootElement();    
    for(Iterator it=root.attributeIterator();it.hasNext();){
           Attribute attribute = (Attribute) it.next();
           String text=attribute.getText();
            System.out.println(text);
     }
Copy after login

5, Set the attributes and text of a node

    newMemberElm.addAttribute("name", "sitinspring");
Copy after login

6, Set the text of the attribute

    Attribute attribute=root.attribute("name");
     attribute.setText("sitinspring");
Copy after login


Insert a node at the specified position

1.Get the node list at the insertion position (list)

2.Call list.add(index,elemnent), determined by index## The insertion position of #element.

Element

Elements can be obtained through the DocumentHelper object. Sample code:

    Element aaa = DocumentHelper.createElement("aaa");
    aaa.setText("aaa");
    List list = root.element("书").elements();
    list.add(1, aaa);
    //更新document
Copy after login


Write document to

XML file


1

, If the document is in English


XMLWriter writer = new XMLWriter(new  FileWriter("output.xml"));
writer.write(document);
writer.close();
Copy after login

2、如果文档含有中文

OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("utf-8");

XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/pc/XML8.xml"), outputFormat);
xmlWriter.write(document);
xmlWriter.close();
Copy after login

PS:出现乱码的原因是因为输出字符集不能识别中文,这样可以通过OutputFormatsetEncoding方法设置为UTF-8,然后再使用XMLWriter这种形参的(OutputStream out, OutputFormat format) 构造方构造方法,就能解决乱码问题了,至于为什么会用createPrettyPrint方法,是因为这样做输出的格式更符合人的阅读习惯。


综合案例

XML8.xml

<?xml version="1.0" encoding="utf-8"?>
<班级 班次="1班" 编号="C1">
	<学生 学号="n1" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>张三</名字>
		<年龄>20</年龄>
		<介绍>不错</介绍>
	</学生>
	<学生 学号="n2" 性别="女" 授课方式="面授" 朋友="n1 n3" 班级编号="C1">
		<名字>李四</名字>
		<年龄>18</年龄>
		<介绍>很好</介绍>
	</学生>
	<学生 学号="n3" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1">
		<名字>王五</名字>
		<年龄>22</年龄>
		<介绍>非常好</介绍>
	</学生>
	<学生 性别="男" 班级编号="C1">
		<名字>小明</名字>
		<年龄>30</年龄>
		<介绍>好</介绍>
	</学生>
</班级>
Copy after login


package com.pc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
 * 
 * @author Switch
 * @function 使用DOM4j解析XML文件
 * 
 */
public class XML8 {
	// 使用DOM4j对XML进行CRUD操作
	public static void main(String[] args) throws Exception {
		// 1.得到解析器
		SAXReader saxReader = new SAXReader();
		// 2.指定解析哪个XML文件
		Document document = saxReader.read(new File("src/com/pc/XML8.xml"));
		// list(document.getRootElement());
		// read(document);
		// readByXPath(document);
		// add(document);
		// delete(document);
		// updateElement(document);
		// updateAttribute(document);
		// addByIndex(document, 3);
	}

	// 更新属性(修改所有班级编号为C2)
	public static void updateAttribute(Document document) throws Exception {
		// 得到所有学生
		List<Element> students = document.getRootElement().elements("学生");
		for (Element e : students) {
			// 修改班级编号
			e.addAttribute("班级编号", "C2");
		}
		updateToXML(document);
	}

	// 更新元素(将所有学生的年龄+3)
	public static void updateElement(Document document) throws Exception {
		// 得到所有学生
		List<Element> students = document.getRootElement().elements("学生");
		for (Element e : students) {
			// 取出年龄
			Element age = e.element("年龄");
			age.setText(Integer.parseInt(age.getTextTrim()) + 3 + "");
		}
		updateToXML(document);
	}

	// 删除元素(删除第一个学生)
	public static void delete(Document document) throws Exception {
		// 找到元素
		Element stu = document.getRootElement().element("学生");
		// 删除
		stu.getParent().remove(stu);

		// 更新
		updateToXML(document);
	}

	// 添加元素到指定位置
	public static void addByIndex(Document document, int index)
			throws Exception {
		// 创建一个元素
		Element newStu = DocumentHelper.createElement("学生");
		newStu.setText("小花");
		// 得到所有学生的list
		List<Element> students = document.getRootElement().elements("学生");
		// 按索引添加
		students.add(index, newStu);

		// 更新
		updateToXML(document);
	}

	// 添加元素(添加一个学生到xml中)
	public static void add(Document document) throws Exception {
		// 创建一个学生节点对象

		Element newStu = DocumentHelper.createElement("学生");
		// 给元素添加属性
		newStu.addAttribute("学号", "n4");
		Element newStuName = DocumentHelper.createElement("名字");
		Element newStuAge = DocumentHelper.createElement("年龄");
		Element newStuIntro = DocumentHelper.createElement("介绍");

		// 把子元素挂载到学生节点下
		newStu.add(newStuName);
		newStu.add(newStuAge);
		newStu.add(newStuIntro);
		// 将学生挂载在根节点下
		document.getRootElement().add(newStu);

		// 更新
		updateToXML(document);
	}

	private static void updateToXML(Document document)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		// 更新xml文件
		// 直接输出会出现中文乱码
		OutputFormat outputFormat = OutputFormat.createPrettyPrint();
		outputFormat.setEncoding("utf-8");

		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(
				"src/com/pc/XML8.xml"), outputFormat);
		xmlWriter.write(document);
		xmlWriter.close();
	}

	// xpath技术,跨层读取某个元素
	public static void readByXPath(Document document) throws Exception {
		// 取出第一个学生
		Element student = (Element) document.selectSingleNode("/班级/学生[1]");
		System.out.println("姓名:" + student.elementText("名字") + "\t年龄:"
				+ student.elementText("年龄") + "\t介绍:"
				+ student.elementText("介绍") + "\t性别:"
				+ student.attributeValue("性别"));
	}

	// 读取指定的某个元素(读取第一个学生的信息)
	public static void read(Document document) throws Exception {
		// 得到根元素
		Element root = document.getRootElement();
		// root.elements("学生"); 取出root元素下的所有学生元素
		// root.element("学生"); 取出root元素下的第一个学生元素
		// 取出root元素下的第一个学生元素
		Element student = (Element) root.elements("学生").get(0);
		System.out.println("姓名:" + student.elementText("名字") + "\t年龄:"
				+ student.elementText("年龄") + "\t介绍:"
				+ student.elementText("介绍") + "\t性别:"
				+ student.attributeValue("性别"));
	}

	// 遍历xml文件
	public static void list(Element element) {
		System.out.println("元素名称:" + element.getName() + "\t元素内容:"
				+ element.getTextTrim());

		Iterator<Element> iterator = element.elementIterator();

		while (iterator.hasNext()) {
			Element e = iterator.next();
			// 递归
			list(e);
		}
	}
}
Copy after login

 以上就是XML编程-DOM4J的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

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

Using Python to merge and deduplicate XML data Using Python to merge and deduplicate XML data Aug 07, 2023 am 11:33 AM

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

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

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

Filtering and sorting XML data using Python Filtering and sorting XML data using Python Aug 07, 2023 pm 04:17 PM

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,

Python implements conversion between XML and JSON Python implements conversion between XML and JSON Aug 07, 2023 pm 07:10 PM

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 Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

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

Python parsing special characters and escape sequences in XML Python parsing special characters and escape sequences in XML Aug 08, 2023 pm 12:46 PM

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

See all articles