XML Programming-DOM4J
XMLProgramming-DOM4J
##Basic Overview
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.
PS:DOM4JOne 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 thereDOM4J?
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"));2.Parse the text in the form of XML, and get the document Object
String text = "<members></members>";
Document document = DocumentHelper.parseText(text);3.Active creationdocumentObject
Document document = DocumentHelper.createDocument();
//创建根节点
Element root = document.addElement("members");PS: Be careful to import the corresponding JAR package.
Node object
1, get the root node of the document
Element root = document.getRootElement();
2, get the child nodes of a node
Element element=node.element(“书名");
3, get the content of the node
String text1=node.getText();
String text2=node.getTextTrim(); // 去掉内容前面和后面的空格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
}5, traverse all child nodes under a certain node
for(Iterator it=root.elementIterator();it.hasNext();){
Element element = (Element) it.next();
// do something
}6, add sub-node under a node
Element ageElm = newMemberElm.addElement("age");
7, set node text
element.setText("29");
8, delete A certain node
//childElm是待删除的节点,parentElm是其父节点
parentElm.remove(childElm);9, add a CDATA node
Element contentElm = infoElm.addElement("content");
contentElm.addCDATA(diary.getContent());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");2, get the text of the attribute
String text=attribute.getText();
3, delete an attribute
Attribute attribute=root.attribute("size");
root.remove(attribute);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);
}5, Set the attributes and text of a node
newMemberElm.addAttribute("name", "sitinspring");
6, Set the text of the attribute
Attribute attribute=root.attribute("name");
attribute.setText("sitinspring");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.
ElementElements 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);
//更新documentXML file
, If the document is in English
XMLWriter writer = new XMLWriter(new FileWriter("output.xml")); writer.write(document); writer.close();
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();
PS:出现乱码的原因是因为输出字符集不能识别中文,这样可以通过OutputFormat的setEncoding方法设置为”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</年龄> <介绍>好</介绍> </学生> </班级>
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);
}
}
} 以上就是XML编程-DOM4J的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20521
7
13634
4
JSON vs. XML: Why RSS Chose XML
May 05, 2025 am 12:01 AM
RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.
Understanding RSS Documents: A Comprehensive Guide
May 09, 2025 am 12:15 AM
RSS documents are a simple subscription mechanism to publish content updates through XML files. 1. The RSS document structure consists of and elements and contains multiple elements. 2. Use RSS readers to subscribe to the channel and extract information by parsing XML. 3. Advanced usage includes filtering and sorting using the feedparser library. 4. Common errors include XML parsing and encoding issues. XML format and encoding need to be verified during debugging. 5. Performance optimization suggestions include cache RSS documents and asynchronous parsing.
Building XML Applications with C : Practical Examples
May 03, 2025 am 12:16 AM
You can use the TinyXML, Pugixml, or libxml2 libraries to process XML data in C. 1) Parse XML files: Use DOM or SAX methods, DOM is suitable for small files, and SAX is suitable for large files. 2) Generate XML file: convert the data structure into XML format and write to the file. Through these steps, XML data can be effectively managed and manipulated.
RSS, XML and the Modern Web: A Content Syndication Deep Dive
May 08, 2025 am 12:14 AM
RSS and XML are still important in the modern web. 1.RSS is used to publish and distribute content, and users can subscribe and get updates through the RSS reader. 2. XML is a markup language and supports data storage and exchange, and RSS files are based on XML.
XML in C : Handling Complex Data Structures
May 02, 2025 am 12:04 AM
Working with XML data structures in C can use the TinyXML or pugixml library. 1) Use the pugixml library to parse and generate XML files. 2) Handle complex nested XML elements, such as book information. 3) Optimize XML processing code, and it is recommended to use efficient libraries and streaming parsing. Through these steps, XML data can be processed efficiently.
Beyond Basics: Advanced RSS Features Enabled by XML
May 07, 2025 am 12:12 AM
RSS enables multimedia content embedding, conditional subscription, and performance and security optimization. 1) Embed multimedia content such as audio and video through tags. 2) Use XML namespace to implement conditional subscriptions, allowing subscribers to filter content based on specific conditions. 3) Optimize the performance and security of RSSFeed through CDATA section and XMLSchema to ensure stability and compliance with standards.
Understanding RSS: An XML Perspective
Apr 25, 2025 am 12:14 AM
RSS is an XML-based format used to publish frequently updated content. 1. RSSfeed organizes information through XML structure, including title, link, description, etc. 2. Creating RSSfeed requires writing in XML structure, adding metadata such as language and release date. 3. Advanced usage can include multimedia files and classified information. 4. Use XML verification tools during debugging to ensure that the required elements exist and are encoded correctly. 5. Optimizing RSSfeed can be achieved by paging, caching and keeping the structure simple. By understanding and applying this knowledge, content can be effectively managed and distributed.
Inside the RSS Document: Essential XML Tags and Attributes
May 03, 2025 am 12:12 AM
The core structure of RSS documents includes XML tags and attributes. The specific parsing and generation steps are as follows: 1. Read XML files, process and tags. 2. Extract,,, etc. tag information. 3. Handle custom tags and attributes to ensure version compatibility. 4. Use cache and asynchronous processing to optimize performance to ensure code readability.





