Java learning path-45: XML quick start-dom4j, XPATH, application cases

Keywords: xml Java encoding Attribute

Chapter 5: dom4j of XML parsing

Introduction to lesson 31 dom4j

https://dom4j.github.io/
rely on

<dependency>
    <groupId>org.dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>2.0.0</version>
</dependency>

demo.xml

<?xml version="1.0" encoding="UTF-8"?>

<list> 
  <person> 
    <name>Zhang San</name>  
    <age>23</age> 
  </person>  
  <person> 
    <name>Li Si</name>  
    <age>24</age> 
  </person> 
</list>

Lesson 32 using dom4j to query xml

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

class Demo {

    public static void main(String[] args) throws DocumentException {
        // Create parser
        SAXReader reader = new SAXReader();

        // Get Document
        Document document = reader.read("demo.xml");

        // Get root element
        Element root = document.getRootElement();

        // Get all person Tags
        List<Element> list = root.elements("person");

        // Traversal tag
        for (Element element : list) {
            Element name = element.element("name");

            // Get value
            String text = name.getText();
            System.out.println(text);
        }
    }
}

Lesson 33 use dom4j to add nodes at the end

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;

class Demo {

    public static void main(String[] args) throws DocumentException, IOException {
        // Create a parser to get Document
        SAXReader reader = new SAXReader();
        Document document = reader.read("demo.xml");

        // Get root element
        Element root = document.getRootElement();

        // Add elements and set content
        Element person = root.element("person");
        Element sex = person.addElement("sex");
        sex.setText("male");

        // Write back and format
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("demo.xml"), format);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}

Lesson 34 use dom4j to add nodes at specific locations

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 java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

class Demo {

    public static void main(String[] args) throws DocumentException, IOException {
        // Create a parser to get Document
        SAXReader reader = new SAXReader();
        Document document = reader.read("demo.xml");
        Element root = document.getRootElement();

        // Add element at specified location
        Element person = root.element("person");
        List<Element> list = person.elements();
        Element sex = DocumentHelper.createElement("sex");
        sex.setText("female");
        list.add(1, sex);

        // Write back and format
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("demo.xml"), format);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}

Lesson 35 operation of encapsulation method in Dom4j

package util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;

public class Dom4jUtil {
    public static Document getDocument(String path) throws DocumentException {
        // Create a parser to get Document
        SAXReader reader = new SAXReader();
        return reader.read(path);
    }

    public static void writeXml(String path, Document document) throws IOException {
        // Write back and format
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path), format);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}

Lesson 36 use dom4j to implement modification

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import util.Dom4jUtil;

import java.io.IOException;

class Demo {

    public static void main(String[] args) throws DocumentException, IOException {
        // Create a parser to get Document
        String path = "demo.xml";
        Document document = Dom4jUtil.getDocument(path);

        // Get root element
        Element root = document.getRootElement();

        Element peron = root.element("person");
        Element sex = peron.element("sex");
        sex.setText("male");

        // Write back and format
        Dom4jUtil.writeXml(path, document);
    }
}

Lesson 37 use dom4j to delete nodes

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import util.Dom4jUtil;

import java.io.IOException;

class Demo {

    public static void main(String[] args) throws DocumentException, IOException {
        String path = "demo.xml";
        Document document = Dom4jUtil.getDocument(path);

        // Get root element
        Element root = document.getRootElement();
        Element person = root.element("person");
        Element sex = person.element("sex");

        // Delete by parent node
        sex.getParent().remove(sex);

        // Write back and format
        Dom4jUtil.writeXml(path, document);
    }
}

Lesson 38 use dom4j to get attribute value

demo.xml

<?xml version="1.0" encoding="UTF-8"?>

<person id="001">
    <name>Zhang San</name>
    <age>23</age>
</person>

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import util.Dom4jUtil;

import java.io.IOException;

class Demo {

    public static void main(String[] args) throws DocumentException, IOException {
        String path = "demo.xml";
        Document document = Dom4jUtil.getDocument(path);

        Element root = document.getRootElement();
        String id = root.attributeValue("id");
        System.out.println(id); // 001

    }
}

Chapter 6: XPATH

Lesson 39 introduction to XPath

dom4j supports xpath operation

Elements can be obtained directly

/a/b/c layer by layer selection
 //B no matter the level, select b directly
 /*All elements
 /a/b[1] first b element
 /a/b[last()] last b element
 //b[@id] as long as there is an id attribute 
//B [@ name = "bbb"] the name attribute is equal to bbb

Lesson 40 use dom4j to support operation 1 of XPATH

jaxen

selectNode()
selectSingleNode()

demo.xml

<?xml version="1.0" encoding="UTF-8"?>

<person id="001">
    <name>Zhang San</name>
    <age>23</age>
</person>

Example: get all name nodes

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import util.Dom4jUtil;

import java.util.List;

class Demo {

    public static void main(String[] args) throws DocumentException {
        String path = "demo.xml";
        Document document = Dom4jUtil.getDocument(path);

        // Get elements
        List<Node> list = document.selectNodes("//name");

        // Ergodic set
        for (Node node : list) {
            String text = node.getText();
            System.out.println(text);
        }

    }
}

Lesson 41 use dom4j to support operation 2 of XPATH

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import util.Dom4jUtil;

class Demo {

    public static void main(String[] args) throws DocumentException {
        String path = "demo.xml";
        Document document = Dom4jUtil.getDocument(path);

        // Get root element
        Node name = document.selectSingleNode("/person[@id='001']/name");
        System.out.println(name.getText());
    }
}

Chapter 7: Cases

Lesson 42-44 student management system implementation - add, delete, query operations

Using xml as database to store student data

rely on

<dependency>
    <groupId>org.dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>2.0.0</version>
</dependency>

demo.xml

<?xml version="1.0" encoding="UTF-8"?>

<list>

</list>

Dom4jUtil.java

package util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.IOException;

public class Dom4jUtil {
    public static Document getDocument(String path) throws DocumentException {
        // Create a parser to get Document
        SAXReader reader = new SAXReader();
        return reader.read(path);
    }

    public static void writeXml(String path, Document document) throws IOException {
        // Write back and format
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path), format);
        xmlWriter.write(document);
        xmlWriter.close();
    }

}

Student.java

package com.pengshiyu.student;

public class Student {
    private String id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }


    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

StudentService.java

package com.pengshiyu.student;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import util.Dom4jUtil;

import java.io.IOException;
import java.util.List;

public class StudentService {
    private static final String path = "demo.xml";

    /**
     * Add data
     *
     * @param student
     * @throws DocumentException
     * @throws IOException
     */
    public static void addStudent(Student student) throws DocumentException, IOException {
        Document document = Dom4jUtil.getDocument(path);
        Element root = document.getRootElement();

        Element person = root.addElement("person");

        Element id = person.addElement("id");
        id.setText(student.getId());

        Element name = person.addElement("name");
        name.setText(student.getName());

        Element age = person.addElement("age");
        age.setText(String.valueOf(student.getAge()));

        Dom4jUtil.writeXml(path, document);
    }

    /**
     * Delete data
     *
     * @param uid
     * @throws IOException
     * @throws DocumentException
     */
    public static void removeStudent(String uid) throws IOException, DocumentException {
        Document document = Dom4jUtil.getDocument(path);

        // Get all IDS
        List<Node> list = document.selectNodes("//id");
        for (Node node : list) {
            String nodeId = node.getText();
            // System.out.println(nodeId);

            // Judge that the id is the same, and remove the parent node through the grandfather node
            if (uid.equals(nodeId)) {
                Element parent = node.getParent();
                Element grandfather = parent.getParent();
                grandfather.remove(parent);
            }
        }
        Dom4jUtil.writeXml(path, document);
    }

    /**
     * Query data
     *
     * @param uid
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Student getStudent(String uid) throws DocumentException {
        Document document = Dom4jUtil.getDocument(path);

        // Get all IDS
        List<Node> list = document.selectNodes("//id");
        for (Node node : list) {
            String nodeId = node.getText();
            // System.out.println(nodeId);

            // Judge that the id is the same, and remove the parent node through the grandfather node
            if (uid.equals(nodeId)) {
                Element parent = node.getParent();

                Student student = new Student();
                student.setId(parent.element("id").getText());
                student.setName(parent.element("name").getText());
                student.setAge(Integer.parseInt(parent.element("age").getText()));

                return student;
            }
        }
        return null;
    }
}

StudentTest.java

package com.pengshiyu.student;

import org.dom4j.DocumentException;
import org.junit.Test;

import java.io.IOException;

public class StudentTest {

    @Test
    public void testAddStudent() throws IOException, DocumentException {
        Student student = new Student("001", "Tom", 23);
        StudentService.addStudent(student);
    }

    @Test
    public void testRemoveStudent() throws IOException, DocumentException {
        StudentService.removeStudent("001");
    }

    @Test
    public void testGEtStudent() throws IOException, DocumentException {
        Student student= StudentService.getStudent("001");
        System.out.println(student);
    }
}

1404 original articles published, 360 praised, 1.28 million visitors+
His message board follow

Posted by ednark on Fri, 14 Feb 2020 07:16:22 -0800