Home Java javaTutorial dom4j creation and parsing xml document example tutorial

dom4j creation and parsing xml document example tutorial

Jun 26, 2017 pm 02:47 PM
dom4j Jianhe document parse

DOM4J Analysis

Features:

1. An intelligent branch of JDOM that incorporates many functions beyond basic XML document representation.

   2. It uses interfaces and abstract basic class methods.

3. It has the characteristics of excellent performance, good flexibility, powerful functions and extreme ease of use.

4. It is an open source file

jar package: dom4j-1.6.1.jar

Create book.xml:

 1 package com.example.xml.dom4j; 2  3 import java.io.FileWriter; 4 import org.dom4j.Document; 5 import org.dom4j.DocumentHelper; 6 import org.dom4j.Element; 7 import org.dom4j.io.OutputFormat; 8 import org.dom4j.io.XMLWriter; 9 /**10  * dom4j创建xml文档示例11  *12  */13 public class Dom4JTest4 {14     public static void main(String[] args) throws Exception {15         // 第二种方式:创建文档并设置文档的根元素节点16         Element root2 = DocumentHelper.createElement("bookstore");17         Document document2 = DocumentHelper.createDocument(root2);18 19         // 添加一级子节点:add之后就返回这个元素20         Element book1 = root2.addElement("book");21         book1.addAttribute("id", "1");22         book1.addAttribute("name", "第一本书");23         // 添加二级子节点24         book1.addElement("name").setText("遇见未知的自己");25         book1.addElement("author").setText("张德芬");26         book1.addElement("year").setText("2014");27         book1.addElement("price").setText("109");28         // 添加一级子节点29         Element book2 = root2.addElement("book");30         book2.addAttribute("id", "2");31         book2.addAttribute("name", "第二本书");32         // 添加二级子节点33         book2.addElement("name").setText("双城记");34         book2.addElement("author").setText("狄更斯");35         book2.addElement("year").setText("2007");36         book2.addElement("price").setText("29");37         38         // 设置缩进为4个空格,并且另起一行为true39         OutputFormat format = new OutputFormat("    ", true);40  41         // 另一种输出方式,记得要调用flush()方法,否则输出的文件中显示空白42         XMLWriter xmlWriter3 = new XMLWriter(new FileWriter("book.xml"),format);43         xmlWriter3.write(document2);44         xmlWriter3.flush();45         // close()方法也可以46 47     }48 }
Copy after login

Run result:

Parse book.xml:

 1 package com.example.xml.dom4j; 2  3 import java.io.File; 4 import java.util.Iterator; 5 import java.util.List; 6 import org.dom4j.Attribute; 7 import org.dom4j.Document; 8 import org.dom4j.DocumentException; 9 import org.dom4j.Element;10 import org.dom4j.io.SAXReader;11 /**12  * dom4j解析xml文档示例13  *14  */15 public class Dom4JTest3 {16     17     public static void main(String[] args) {18         // 解析books.xml文件19         // 创建SAXReader的对象reader20         SAXReader reader = new SAXReader();21         try {22             // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。23             Document document = reader.read(new File("book.xml"));24             // 通过document对象获取根节点bookstore25             Element bookStore = document.getRootElement();26             System.out.println("根节点名:"+bookStore.getName());27             // 通过element对象的elementIterator方法获取迭代器28             Iterator it = bookStore.elementIterator();29             // 遍历迭代器,获取根节点中的信息(书籍)30             while (it.hasNext()) {31                 System.out.println("=====开始遍历子节点=====");32                 Element book = (Element) it.next();33                 System.out.println("子节点名:"+book.getName());34                 // 获取book的属性名以及 属性值35                 List<Attribute> bookAttrs = book.attributes();36                 for (Attribute attr : bookAttrs) {37                     System.out.println("属性名:" + attr.getName() + "--属性值:"38                             + attr.getValue());39                 }40                 Iterator itt = book.elementIterator();41                 while (itt.hasNext()) {42                     Element bookChild = (Element) itt.next();43                     System.out.println("节点名:" + bookChild.getName() + "--节点值:" + bookChild.getStringValue());44                 }45                 System.out.println("=====结束遍历该节点=====");46             }47         } catch (DocumentException e) {48             e.printStackTrace();49         }50     }51 52 }
Copy after login

Run result:

The above is the detailed content of dom4j creation and parsing xml document example tutorial. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to add redline to Word document How to add redline to Word document Mar 01, 2024 am 09:40 AM

It is 395 words, which is 495. This article will show you how to add red lines in Word documents. Redlining a document refers to making modifications to the document so that users can clearly see the changes. This feature is very important when multiple people are editing a document together. What redline means Marking a document Redlining means using red lines or callouts to indicate changes, edits, or revisions to a document. The term was inspired by the practice of using a red pen to mark printed documents. Redline comments are widely used in different scenarios, such as clearly showing recommended changes to authors, editors, and reviewers when editing a document. Propose changes and modifications in legal agreements or contracts Provide constructive criticism and suggestions on papers, presentations, etc. How to give W

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

Word document is blank when opening on Windows 11/10 Word document is blank when opening on Windows 11/10 Mar 11, 2024 am 09:34 AM

When you encounter a blank page issue when opening a Word document on a Windows 11/10 computer, you may need to perform repairs to resolve the situation. There are various sources of this problem, one of the most common being a corrupted document itself. Furthermore, corruption of Office files may also lead to similar situations. Therefore, the fixes provided in this article may be helpful to you. You can try to use some tools to repair the damaged Word document, or try to convert the document to another format and reopen it. In addition, checking whether the Office software in the system needs to be updated is also a way to solve this problem. By following these simple steps, you may be able to fix Word document blank when opening Word document on Win

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

Parsing Wormhole NTT: an open framework for any Token Parsing Wormhole NTT: an open framework for any Token Mar 05, 2024 pm 12:46 PM

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

Old games with new graphics! RTX Remix takes you back to classic 2.0! Old games with new graphics! RTX Remix takes you back to classic 2.0! Mar 12, 2024 pm 07:50 PM

On January 23, 2024, Beijing time, NVIDIARTXRemix was fully launched for public testing. Download link: https://www.nvidia.cn/geforce/rtx-remix/What is RTXRemix? It is a free mod platform based on NVIDIA Omniverse, dedicated to helping modders quickly create and share #RTXON versions of classic old games. We can simply understand it as an external program, which will not change the engine of old games; rather, it will not change the engine of old games; Take over a series of tools such as graphics rendering pipeline/scene management while the game is running, and combine it with NVIDIA full ray tracing, DLSS, Reflex and other technologies to achieve significant changes.

Detailed explanation of Word document operation: merge two pages into one Detailed explanation of Word document operation: merge two pages into one Mar 26, 2024 am 08:18 AM

Word documents are one of the most frequently used applications in our daily work and study. When working with documents, you may sometimes encounter a situation where you need to merge two pages into one. This article will introduce in detail how to merge two pages into one page in a Word document to help readers handle document layout more efficiently. In Word documents, the operation of merging two pages into one is usually used to save paper and printing costs, or to make the document more compact and neat. The following are the specific steps to merge two pages into one: Step 1: Open the Word that needs to be operated

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

See all articles