1. Use dom4j to support XPATH operations
―You can directly obtain an element without layer by layer analysis
How to use XPATH:
The first form: /AAA/BBB/CCC, one/ represents a layer, indicating that the CCC below BBB below AAA is obtained
The second form: //BBB, which means that if the name is the same as this one, you can get it as long as the name is BBB. //DDD/BBB: Get all BBBs below DDD
The third form: /AAA/BBB/CCC/*, get all the elements below BBBB and CCC below. /*/*/*/BBB means limiting the first three layers. No matter what the name of the first three layers, you can get all the BBBs below it. //*, get all the elements.
The fourth form: /AAA/BBB[1], the first BBB below AAA. /AAA/BBB[last()] means that the last BBB below AAA is obtained
The fifth form: //@id, means that as long as there is an id attribute on the label, you can get all id attributes //BBB[@id], you can get all id attributes as long as you have an id attribute on the BBB, you can get the BBB with an id attribute.
The sixth form: //BBB[@id='b1'], obtain all BBBs with attribute id and value b1
2. Use xpath
By default, dom4j does not support xpath.
To support, you need to import jar packages, jaxen-1.1-beta-6.jar
There are two methods: selectNodes("xpath tag expression"); get all elements, return List, selectSingleNode("xpath tag expression"); get one element, return Node
1. Query the values of all name elements in xml
Steps: Get the document, use the method selectNodes("xpath tag expression");
public static void Test1() throws Exception { Document document = Dom4jUtils.getDocument(Dom4jUtils.PATH); List<Node> list = document.selectNodes("//name"); for (Node node : list) { //node is the specific value of each element//Get the specific value of each element String s = node.getText(); System.out.println(s); } }2. Query the value of the first name in xml. Steps: Get the document first, and then build the xpath expression.
public static void Test2() throws Exception{ Document document = Dom4jUtils.getDocument(Dom4jUtils.PATH); Node name1 = document.selectSingleNode("//p1[@id1='aaa']/name"); //Get the value of name String s1 = name1.getText(); System.out.println(s1); }2. Case analysis
Add, delete, query
student.xml
<?xml version="1.0" encoding="UTF-8"?><student> <stu> <id>01</id> <name>zhangsan</name> <age>20</age> </stu> <stu> <id>02</id> <name>lisi</name> <age>19</age> </stu> </stu>
student.java
package cn.qing.ov;public class Student {private String id;private String name;private String 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 String getAge() {return age;}public void setAge(String age) {this.age = age;}@Override public String toString() {return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";}}stuService.java
package cn.qing.service;import java.io.FileOutputStream;import java.io.Writer;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.Node;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import cn.qing.ov.Student;public class StuService {//Add public static void addStu(Student student) throws Exception {SAXReader saxReader = new SAXReader();Document document = saxReader.read("src/student.xml");Element root = document.getRootElement();//Add stuElement on the root node stu = root.addElement("stu");//Add id, name, ageElement id1 = stu.addElement("id");Element name1 = stu.addElement("name");Element age1 = stu.addElement("age");//Add the values id1.setText(student.getId());name1.setText(student.getName());age1.setText(student.getAge());//Write back to xml OutputFormat format = OutputFormat.createPrettyPrint();XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/student.xml"),format);xmlWriter.write(document);xmlWriter.close();}//Delete, delete according to the student ID/** * * @param id * @throws Exception * 1. Create a parser* 2. Obtain document * 3. Get the ID in xml, use xpath, and return a list collection* 4. Iterate over the list and determine whether the value in the collection is the same as the id passed in * 5. If the same, delete the stu where the id is located* 6. Write back */public static void delStu(String id) throws Exception {SAXReader saxReader = new SAXReader();Document document = saxReader.read("src/student.xml");List<Node> list = document.selectNodes("//id");for (Node node : list) {String idv = node.getText();//Judge whether it is the same as the passed value if(idv.equals(id)) {//Get the node of stu Element stu = node.getParent();//Delete is to delete it through the parent node Element student = stu.getParent();stu.remove(stu);}}OutputFormat format =OutputFormat.createPrettyPrint();XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/student.xml"),format);xmlWriter.write(document);xmlWriter.close();}//Query public static Student selStu(String id) throws Exception {SAXReader saxReader = new SAXReader();Document document = saxReader.read("src/student.xml");List<Node> list = document.selectNodes("//id");Student student = new Student();for (Node node : list) {//node is the value of each id String idv = node.getText();if(idv.equals(id)) {Element stu = node.getParent();String namev = stu.element("name").getText();String agev = stu.element("age").getText();student.setId(idv);student.setName(namev);student.setAge(agev);}} return student;}}Test Test.java
package cn.qing.test;import cn.qing.ov.Student;import cn.qing.service.StuService;public class Test {public static void main(String[] args) throws Exception {//testAdd();//testDel();testSel();}//test Add method public static void testAdd() throws Exception {//Create student object Student stu = new Student();stu.setId("03");stu.setName("wangwu");stu.setAge("18");StuService.addStu(stu);}//Test delete method public static void testDel() throws Exception {StuService.delStu("03");}//Test query method public static void testSel() throws Exception {Student student = StuService.selStu("02");System.out.println(student.toString());}}For each type, it can be set in different packages, programming ideas
Summarize
The above is all the content of this article about xpath in Java programming, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!