当前位置:网站首页>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
边栏推荐
- Android本地Sqlite数据库的备份和还原
- 程序员成长第八篇:做好测试工作
- Small case of function transfer parameters
- Association modeling method in SAP segw transaction code
- Put functions in modules
- Asemi rectifier bridge hd06 parameters, hd06 pictures, hd06 applications
- How to choose note taking software? Comparison and evaluation of notion, flowus and WOLAI
- [deep learning paper notes] hnf-netv2 for segmentation of brain tumors using multimodal MR imaging
- Shu tianmeng map × Weiyan technology - Dream map database circle of friends + 1
- Cf:a. the third three number problem
猜你喜欢
蜀天梦图×微言科技丨达梦图数据库朋友圈+1
先写API文档还是先写代码?
Shu tianmeng map × Weiyan technology - Dream map database circle of friends + 1
SAE international strategic investment geometry partner
百日完成国产数据库opengausss的开源任务--openGuass极简版3.0.0安装教程
UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xe6 in position 76131: invalid continuation byt
It's too convenient. You can complete the code release and approval by nailing it!
百度杯”CTF比赛 2017 二月场,Web:爆破-2
Although the volume and price fall, why are the structural deposits of commercial banks favored by listed companies?
"Baidu Cup" CTF competition in September, web:sql
随机推荐
Halcon template matching actual code (I)
Talk about seven ways to realize asynchronous programming
Concurrent performance test of SAP Spartacus with JMeter
JPA规范总结和整理
RHCSA10
MATLAB论文图表标准格式输出(干货)
Apicloud studio3 API management and debugging tutorial
[notes of in-depth study paper]uctransnet: rethink the jumping connection in u-net from the perspective of transformer channel
Shandong University Summer Training - 20220620
什么是网络端口
[深度学习论文笔记]使用多模态MR成像分割脑肿瘤的HNF-Netv2
Rocky basic command 3
Overflow toolbar control in SAP ui5 view
【Hot100】34. 在排序数组中查找元素的第一个和最后一个位置
多人合作项目查看每个人写了多少行代码
[深度学习论文笔记]UCTransNet:从transformer的通道角度重新思考U-Net中的跳跃连接
Flutter draws animation effects of wave movement, curves and line graphs
Hiengine: comparable to the local cloud native memory database engine
南理工在线交流群
山东大学暑期实训一20220620