DOM4j and source code analysis

DOM4J

Documentation: https://dom4j.github.io/javadoc/1.6.1/

Local documentation: dom4j-1.6.1\docs\index.html

Principles of XML Parsing Technology

  1. Whether it is an html file or an xml file, they are all tagged documents, and can be parsed using the dom technology developed by the w3c organization
  2. The document object represents the entire document (it can be an html document or an xml document)
    insert image description here

Introduction to XML Parsing Technology

● Early JDK provided us with two xml parsing technologies DOM and Sax Introduction

  1. The dom parsing technology is formulated by the W3C organization, and all programming languages ​​use the characteristics of their own language to implement this parsing technology. Java also implements dom technology analysis
  2. Sun has upgraded the dom parsing technology in the JDK5 version: SAX (Simple API for XML) SAX parsing, which uses a similar event mechanism to tell the user what is currently being parsed through a callback. It reads the xml file line by line for parsing without creating a large number of dom objects. So it is better than Dom parsing in performance when parsing xml
  3. These two technologies are outdated, just know that there are two technologies

● Third-party XML parsing technology

  1. jdom is encapsulated on the basis of dom
  2. dom4j encapsulates jdom again.
  3. pull is mainly used in the development of Android mobile phones. It is very similar to sax and uses an event mechanism to parse xml files.

Introduction to DOM4J

  1. Dom4j is a simple, flexible open source library (for parsing/processing XML files). Dom4j was spun out and developed independently by the people who developed JDOM in the early days.
  2. Unlike JDOM, dom4j uses interfaces and abstract base classes. Although Dom4j's API is relatively complex, it provides better flexibility than JDOM.
  3. Dom4j is a very good Java XML API with excellent performance, powerful functions and extremely easy to use. Dom4j is now used by many software.

In DOM4j, there are three ways to obtain Document objects

● Develop dom4j To import dom4j package
1. Read XML file and get document object
SAXReader reader = new SAXReader(); //Create a parser
Document document = reader.read(new File(“src/input.xml”) );//XML Document

2. Parse the text in XML form to get the document object
String text = "";
Document document = DocumentHelper.parseText(text);

3. Actively create document objects.
Document document = DocumentHelper.createDocument(); //Create root node
Element root = document.addElement(“members”);

DOM4j application example

source code

insert image description here

CRUD

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;
import org.junit.jupiter.api.Test;

import java.io.File;

import java.io.FileOutputStream;
import java.util.List;

public class Dom4j_ {
    
    

Specify to read the information of the first student is dom4j+xpath

   @Test
   public void readOne() throws DocumentException {
    
    
       //得到一个解析器
       SAXReader reader = new SAXReader();
       //代码技巧->debug 看看 document 对象的属性
       //分析了 document 对象的底层结构
       Document document = reader.read(new File("src/students.xml"));

       //1. 得到 rootElement, 你是 OOP
       Element rootElement = document.getRootElement();
       //2. 获取第一个学生
       Element student = (Element) rootElement.elements("student").get(1);
       //3. 输出该信息
       System.out.println("该学生的信息= " + student.element("name").getText() + " " +
               student.element("age").getText() + " " +
               student.element("resume").getText() +
               student.element("gender").getText());
       //4. 获取 student 元素的属性
       System.out.println("id= " + student.attributeValue("id"));
   }
 加元素(要求: 添加一个学生到 xml 中) [不要求,使用少,了解]
   @Test
   public void add() throws Exception {
    
    
       //1.得到解析器
       SAXReader saxReader = new SAXReader();
       //2.指定解析哪个 xml 文件
       Document document = saxReader.read(new File("src/students.xml"));
       //首先我们来创建一个学生节点对象
       Element newStu = DocumentHelper.createElement("student");
       Element newStu_name = DocumentHelper.createElement("name");
       //如何给元素添加属性
       newStu.addAttribute("id", "04");
       newStu_name.setText("宋江");
       //创建 age 元素
       Element newStu_age = DocumentHelper.createElement("age");
       newStu_age.setText("23");
       //创建 resume 元素
       Element newStu_intro = DocumentHelper.createElement("resume");
       newStu_intro.setText("梁山老大");

       //把三个子元素(节点)加到 newStu 下
       newStu.add(newStu_name);
       newStu.add(newStu_age);
       newStu.add(newStu_intro);
       //再把 newStu 节点加到根元素
       document.getRootElement().add(newStu);
       //直接输出会出现中文乱码:
       OutputFormat output = OutputFormat.createPrettyPrint();
       output.setEncoding("utf-8");//输出的编码 utf-8
       //把我们的 xml 文件更新
       // lets write to a file
       //new FileOutputStream(new File("src/myClass.xml"))
       //使用到 io 编程 FileOutputStream 就是文件字节输出流
       XMLWriter writer = new XMLWriter(
               new FileOutputStream(new File("src/students.xml")), output);
       writer.write(document);
       writer.close();
   }
   
  • //Delete elements (requirement: delete the first student) Use less, understand
   @Test

   public void del() throws Exception {
    
    
       //1.得到解析器
       SAXReader saxReader = new SAXReader();
       //2.指定解析哪个 xml 文件
       Document document = saxReader.read(new File("src/students.xml"));
       //找到该元素第一个学生
       Element stu = (Element)
               document.getRootElement().elements("student").get(2);
       //删除元素
       stu.getParent().remove(stu);
       // //删除元素的某个属性
       // stu.remove(stu.attribute("id"));
       //更新 xml
       //直接输出会出现中文乱码:
       OutputFormat output = OutputFormat.createPrettyPrint();
       韩顺平 Java 工程师
       output.setEncoding("utf-8");//输出的编码 utf-8
       //把我们的 xml 文件更新
       XMLWriter writer = new XMLWriter(
               new FileOutputStream(new File("src/students.xml")), output);
       writer.write(document);
       writer.close();
       System.out.println("删除成功~");
   }

Update element (requires age of all students +3) use less, understand

    @Test
    public void update() throws Exception {
    
    
        //1.得到解析器
        SAXReader saxReader = new SAXReader();
        //2.指定解析哪个 xml 文件
        Document document = saxReader.read(new File("src/students.xml"));
     
        //得到所有学生的年龄
        List<Element> students = document.getRootElement().elements("student");
        //遍历, 所有的学生元素的 age+3
        for (Element student : students) {
    
    
            //取出年龄
            Element age = student.element("age");
            age.setText((Integer.parseInt(age.getText()) + 3) + "");
        }
        //更新
        //直接输出会出现中文乱码:
        OutputFormat output = OutputFormat.createPrettyPrint();
        output.setEncoding("utf-8");//输出的编码 utf-8
        //把我们的 xml 文件更新
        XMLWriter writer = new XMLWriter(
                new FileOutputStream(new File("src/students.xml")), output);
        writer.write(document);
        writer.close();
        System.out.println("更新成功~");
    }
}

Guess you like

Origin blog.csdn.net/apple_67445472/article/details/131771431