当前位置:网站首页>Parsing XML using Dom4j
Parsing XML using Dom4j
2022-07-05 13:19:00 【Full stack programmer webmaster】
dom4j It's a Java Of XML API, Be similar to jdom, For reading and writing XML Of documents .dom4j It's a very, very good Java XML API, Excellent performance 、 Powerful and extremely easy to use features , It is also an open source Software , Can be in SourceForge Find it on the .
To the mainstream Java XML API Performance in progress 、 Function and usability evaluation ,dom4j It's excellent in that respect . Now you can see more and more Java Software All in use dom4j Read and write XML, for example Hibernate, Include sun The company's own JAXM Also used. Dom4j.
Use Dom4j Development , Need to download dom4j Corresponding jar file
1. Download from the official website : http://www.dom4j.org/dom4j-1.6.1/
2.dom4j yes sourceforge.net An open source project on , So you can http://sourceforge.net/projects/dom4j Download its latest version .
For downloaded zip The effect of decompressing the file is as follows :
open dom4j-1.6.1 The unzip file of
You can see here that there are docs Folder for help , There is also a need to use dom4j analysis xml Of documents dom4j-1.6.1.jar file . We just have to take dom4j-1.6.1.jar The file can be used when it is built into the project we develop dom4j Developed .
Now I will Myeclipse establish Java Take the construction method of the project as an example .
First create a demo project , stay demo Create a lib file , hold dom4j-1.6.1.jar File copy to lib in , And then right-click dom4j-1.6.1jar file
Click on Add to Build Path It can be built into the project .
remarks : If we're going to web Project development , We just need to copy it to web-inf/lib Just go to the middle , Will be automatically built to web In the project .
In the process of project development, you can refer to docs The folder ( Help document ), find index.html open , Click on Quick start You can learn through help documents dom4j Conduct xml Parsing .
Now I think api The important methods of translation are described as follows :
One 、DOM4j in , get Document There are three ways to object :
- 1. Read XML file , get document object
- SAXReader reader = new SAXReader();
- Document document = reader.read(new File(“csdn.xml”));
- 2. analysis XML Formal text , obtain document object .
- String text = “<csdn></csdn>”;
- Document document = DocumentHelper.parseText(text);
- 3. Active creation document object .
- Document document = DocumentHelper.createDocument(); // Create a root node
- Element root = document.addElement(“csdn”);
Two 、 How to operate node objects
- 1. Get the root node of the document .
- Element root = document.getRootElement();
- 2. Get the children of a node .
- Element element=node.element(“ Four masterpieces ”);
- 3. Get the text of the node
- String text=node.getText();
- 4. Get all the names under a node “csdn” Child nodes of , And traverse .
- List nodes = rootElm.elements(“csdn”);
- for (Iterator it = nodes.iterator(); it.hasNext();) {
- Element elm = (Element) it.next();
- // do something
- }
- 5. Traverse all the child nodes under a certain node .
- for(Iterator it=root.elementIterator();it.hasNext();){
- Element element = (Element) it.next();
- // do something
- }
- 6. Add children under a node
- Element elm = newElm.addElement(“ Dynasty ”);
- 7. Set node text . elm.setText(“ The Ming dynasty ”);
- 8. Delete a node .//childElement Is the node to be deleted ,parentElement It's the parent node parentElement.remove(childElment);
- 9. Add one CDATA node .Element contentElm = infoElm.addElement(“content”);contentElm.addCDATA(“cdata Area ”);
3、 ... and 、 Operation of attribute method of node object
- 1. Get an attribute under a node Element root=document.getRootElement(); // Property name name
- Attribute attribute=root.attribute(“id”);
- 2. Get attribute text
- String text=attribute.getText();
- 3. Delete a property Attribute attribute=root.attribute(“size”); root.remove(attribute);
- 4. Traverse all properties 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);
- }
- 5. Set the attributes and text of a node . newMemberElm.addAttribute(“name”, “sitinspring”);
- 6. Set attribute text Attribute attribute=root.attribute(“name”); attribute.setText(“csdn”);
Four 、 Write the document to XML file
- 1. All the documents are in English , No coding , The form of direct writing .
- XMLWriter writer = new XMLWriter(new FileWriter(“ot.xml”));
- writer.write(document);
- writer.close();
- 2. The document contains Chinese , Set the encoding format to write to .
- OutputFormat format = OutputFormat.createPrettyPrint();// When creating a file output , Auto indent format
- format.setEncoding(“UTF-8”);// Set encoding
- XMLWriter writer = new XMLWriter(newFileWriter(“output.xml”),format);
- writer.write(document);
- writer.close();
5、 ... and 、 String and XML Transformation
- 1. Converts a string to XML
- String text = “<csdn> <java>Java class </java></csdn>”;
- Document document = DocumentHelper.parseText(text);
- 2. Of a document or node XML Convert to string .
- SAXReader reader = new SAXReader();
- Document document = reader.read(new File(“csdn.xml”));
- Element root=document.getRootElement();
- String docXmlText=document.asXML();
- String rootXmlText=root.asXML();
- Element memberElm=root.element(“csdn”);
- String memberXmlText=memberElm.asXML();
6、 ... and 、 Case study ( analysis sida.xml Document and carry out curd The operation of )
1.sida.xml Describe the operation of the four masterpieces , The contents of the document are as follows
- <?xml version=“1.0” encoding=“UTF-8”?>
- < Four masterpieces >
- < Journey to the west id=“x001”>
- < author > Wu chengen 1</ author >
- < author > Wu chengen 2</ author >
- < Dynasty > The Ming dynasty </ Dynasty >
- </ Journey to the west >
- < A dream of red mansions id=“x002”>
- < author > Cao xueqin </ author >
- </ A dream of red mansions >
- </ Four masterpieces >
2. Parse class test operation
- package dom4j;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.FileWriter;
- import java.io.OutputStreamWriter;
- import java.nio.charset.Charset;
- import java.nio.charset.CharsetEncoder;
- import java.util.Iterator;
- import java.util.List;
- import org.dom4j.Attribute;
- import org.dom4j.Document;
- import org.dom4j.Element;
- import org.dom4j.io.OutputFormat;
- import org.dom4j.io.SAXReader;
- import org.dom4j.io.XMLWriter;
- import org.junit.Test;
- public class Demo01 {
- @Test
- public void test() throws Exception {
- // establish saxReader object
- SAXReader reader = new SAXReader();
- // adopt read Method to read a file convert to Document object
- Document document = reader.read(new File(“src/dom4j/sida.xml”));
- // Get the root node element object
- Element node = document.getRootElement();
- // Traverse all element nodes
- listNodes(node);
- // Get the four famous elements in the node , The name of the child node is the element node of the dream of Red Mansions .
- Element element = node.element(“ A dream of red mansions ”);
- // obtain element Of id Attribute node object
- Attribute attr = element.attribute(“id”);
- // Delete attribute
- element.remove(attr);
- // Add new properties
- element.addAttribute(“name”, “ author ”);
- // Add the node of dynasty element to the element node of dream of Red Mansions
- Element newElement = element.addElement(“ Dynasty ”);
- newElement.setText(“ Qing Dynasty ”);
- // obtain element Author element node object in
- Element author = element.element(“ author ”);
- // Delete element nodes
- boolean flag = element.remove(author);
- // return true Code deletion succeeded , Otherwise failure
- System.out.println(flag);
- // add to CDATA Area
- element.addCDATA(“ A dream of red mansions , It's a love story .”);
- // Write to a new file
- writer(document);
- }
- /**
- * hold document Object to write to a new file
- *
- * @param document
- * @throws Exception
- */
- public void writer(Document document) throws Exception {
- // Compact format
- // OutputFormat format = OutputFormat.createCompactFormat();
- // The format of typesetting indentation
- OutputFormat format = OutputFormat.createPrettyPrint();
- // Set encoding
- format.setEncoding(“UTF-8”);
- // establish XMLWriter object , Specify write file and encoding format
- // XMLWriter writer = new XMLWriter(new FileWriter(new
- // File(“src//a.xml”)),format);
- XMLWriter writer = new XMLWriter(new OutputStreamWriter(
- new FileOutputStream(new File(“src//a.xml”)), “UTF-8”), format);
- // write in
- writer.write(document);
- // Write now
- writer.flush();
- // Close operation
- writer.close();
- }
- /**
- * Traverse all of the following under the current node element ( Elemental ) Child node
- *
- * @param node
- */
- public void listNodes(Element node) {
- System.out.println(“ The name of the current node ::” + node.getName());
- // Get all the attribute nodes of the current node
- List<Attribute> list = node.attributes();
- // Traverse attribute nodes
- for (Attribute attr : list) {
- System.out.println(attr.getText() + “—–” + attr.getName()
- + “—” + attr.getValue());
- }
- if (!(node.getTextTrim().equals(“”))) {
- System.out.println(“ Text content ::::” + node.getText());
- }
- // Current node face child node iterator
- Iterator<Element> it = node.elementIterator();
- // Traverse
- while (it.hasNext()) {
- // Get a child node object
- Element e = it.next();
- // Traverse the child nodes
- listNodes(e);
- }
- }
- /**
- * Introduce Element Medium element Methods and elements Use of methods
- *
- * @param node
- */
- public void elementMethod(Element node) {
- // obtain node In nodes , The element name of the child node is the element node of journey to the West .
- Element e = node.element(“ Journey to the west ”);
- // Get element node of journey to the West , The child node is the author's element node ( You can see that you can only get the first author element node )
- Element author = e.element(“ author ”);
- System.out.println(e.getName() + “—-” + author.getText());
- // Get the element node of journey to the West in , All child nodes are named author element nodes .
- List<Element> authors = e.elements(“ author ”);
- for (Element aut : authors) {
- System.out.println(aut.getText());
- }
- // Get the element node of journey to the West Children of all elements .
- List<Element> elements = e.elements();
- for (Element el : elements) {
- System.out.println(el.getText());
- }
- }
- }
Comment part of the code appropriately and observe the running effect , Practice over and over again , I hope you are right dom4j Have a further understanding of .
7、 ... and 、 String and XML Mutual conversion cases
- package dom4j;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.OutputStreamWriter;
- import org.dom4j.Document;
- import org.dom4j.DocumentHelper;
- import org.dom4j.Element;
- import org.dom4j.io.OutputFormat;
- import org.dom4j.io.SAXReader;
- import org.dom4j.io.XMLWriter;
- import org.junit.Test;
- public class Demo02 {
- @Test
- public void test() throws Exception {
- // establish saxreader object
- SAXReader reader = new SAXReader();
- // Read a file , Convert this file into Document object
- Document document = reader.read(new File(“src//c.xml”));
- // Get the root element
- Element root = document.getRootElement();
- // Convert the document into a string
- String docXmlText = document.asXML();
- System.out.println(docXmlText);
- System.out.println(“—————————“);
- // csdn Content of element tag root transformation
- String rootXmlText = root.asXML();
- System.out.println(rootXmlText);
- System.out.println(“—————————“);
- // obtain java The element tag Internal content
- Element e = root.element(“java”);
- System.out.println(e.asXML());
- }
- /**
- * Create a document object Go to document Add node elements to the object Transfer to xml file
- *
- * @throws Exception
- */
- public void test2() throws Exception {
- Document document = DocumentHelper.createDocument();// Create a root node
- Element root = document.addElement(“csdn”);
- Element java = root.addElement(“java”);
- java.setText(“java class ”);
- Element ios = root.addElement(“ios”);
- ios.setText(“ios class ”);
- writer(document);
- }
- /**
- * Convert a text string Document object
- *
- * @throws Exception
- */
- public void test1() throws Exception {
- String text = “<csdn><java>Java class </java><net>Net class </net></csdn>”;
- Document document = DocumentHelper.parseText(text);
- Element e = document.getRootElement();
- System.out.println(e.getName());
- writer(document);
- }
- /**
- * hold document Object to write to a new file
- *
- * @param document
- * @throws Exception
- */
- public void writer(Document document) throws Exception {
- // Compact format
- // OutputFormat format = OutputFormat.createCompactFormat();
- // The format of typesetting indentation
- OutputFormat format = OutputFormat.createPrettyPrint();
- // Set encoding
- format.setEncoding(“UTF-8”);
- // establish XMLWriter object , Specify write file and encoding format
- // XMLWriter writer = new XMLWriter(new FileWriter(new
- // File(“src//a.xml”)),format);
- XMLWriter writer = new XMLWriter(new OutputStreamWriter(
- new FileOutputStream(new File(“src//c.xml”)), “UTF-8”), format);
- // write in
- writer.write(document);
- // Write now
- writer.flush();
- // Close operation
- writer.close();
- }
- }
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/109288.html Link to the original text :https://javaforall.cn
边栏推荐
- Write API documents first or code first?
- go 数组与切片
- Solve Unicode decodeerror: 'GBK' codec can't decode byte 0xa2 in position 107
- LB10S-ASEMI整流桥LB10S
- mysql econnreset_ Nodejs socket error handling error: read econnreset
- Concurrent performance test of SAP Spartacus with JMeter
- 从外卖点单浅谈伪需求
- Android本地Sqlite数据库的备份和还原
- [深度学习论文笔记]TransBTSV2: Wider Instead of Deeper Transformer for Medical Image Segmentation
- 初次使用腾讯云,解决只能使用webshell连接,不能使用ssh连接。
猜你喜欢

Actual combat simulation │ JWT login authentication

Navigation property and entityset usage in SAP segw transaction code

Cf:a. the third three number problem

FPGA 学习笔记:Vivado 2019.1 添加 IP MicroBlaze

Developers, is cloud native database the future?

STM32 and motor development (from architecture diagram to documentation)

Pandora IOT development board learning (HAL Library) - Experiment 7 window watchdog experiment (learning notes)

Discussion on error messages and API versions of SAP ui5 getsaplogonlanguage is not a function

ABAP editor in SAP segw transaction code

【服务器数据恢复】某品牌服务器存储raid5数据恢复案例
随机推荐
Sorry, we can't open xxxxx Docx, because there is a problem with the content (repackaging problem)
#从源头解决# 自定义头文件在VS上出现“无法打开源文件“XX.h“的问题
[深度学习论文笔记]使用多模态MR成像分割脑肿瘤的HNF-Netv2
量价虽降,商业银行结构性存款为何受上市公司所偏爱?
Natural language processing series (I) introduction overview
The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)
初次使用腾讯云,解决只能使用webshell连接,不能使用ssh连接。
Flutter 3.0更新后如何应用到小程序开发中
阿里云SLB负载均衡产品基本概念与购买流程
Although the volume and price fall, why are the structural deposits of commercial banks favored by listed companies?
Changing JS code has no effect
FPGA 学习笔记:Vivado 2019.1 添加 IP MicroBlaze
Jenkins installation
MySQL - database query - sort query, paging query
Go pointer
Alibaba cloud SLB load balancing product basic concept and purchase process
DataPipeline双料入选中国信通院2022数智化图谱、数据库发展报告
What is a network port
Backup and restore of Android local SQLite database
Principle and configuration of RSTP protocol