当前位置:网站首页>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
边栏推荐
- 关于 Notion-Like 工具的反思和畅想
- Difference between avc1 and H264
- mysql获得时间
- [notes of in-depth study paper]uctransnet: rethink the jumping connection in u-net from the perspective of transformer channel
- 初次使用腾讯云,解决只能使用webshell连接,不能使用ssh连接。
- MySQL - database query - sort query, paging query
- Android本地Sqlite数据库的备份和还原
- Flutter 绘制波浪移动动画效果,曲线和折线图
- Go pointer
- Asemi rectifier bridge hd06 parameters, hd06 pictures, hd06 applications
猜你喜欢
《2022年中国银行业RPA供应商实力矩阵分析》研究报告正式启动
爱可生SQLe审核工具顺利完成信通院‘SQL质量管理平台分级能力’评测
潘多拉 IOT 开发板学习(HAL 库)—— 实验7 窗口看门狗实验(学习笔记)
Overflow toolbar control in SAP ui5 view
Alibaba cloud SLB load balancing product basic concept and purchase process
南理工在线交流群
Changing JS code has no effect
Talk about seven ways to realize asynchronous programming
简单上手的页面请求和解析案例
初次使用腾讯云,解决只能使用webshell连接,不能使用ssh连接。
随机推荐
Principle and performance analysis of lepton lossless compression
Could not set property ‘id‘ of ‘class XX‘ with value ‘XX‘ argument type mismatch 解决办法
Flutter InkWell & Ink组件
leetcode 10. Regular Expression Matching 正则表达式匹配 (困难)
Detailed explanation of navigation component of openharmony application development
Run, open circuit
Flutter draws animation effects of wave movement, curves and line graphs
Le rapport de recherche sur l'analyse matricielle de la Force des fournisseurs de RPA dans le secteur bancaire chinois en 2022 a été officiellement lancé.
简单上手的页面请求和解析案例
Introduction to sap ui5 flexiblecolumnlayout control
Rocky basics 1
峰会回顾|保旺达-合规和安全双驱动的数据安全整体防护体系
What is a network port
MSTP and eth trunk
OpenHarmony应用开发之Navigation组件详解
【每日一题】1200. 最小绝对差
Rocky基础知识1
南理工在线交流群
Hiengine: comparable to the local cloud native memory database engine
[深度学习论文笔记]TransBTSV2: Wider Instead of Deeper Transformer for Medical Image Segmentation