How to read XML document with xpath using dom4j library

You can create an xml document using SAXReader as given sample below.

 
 
// Get the SAXReader object
SAXReader reader = new SAXReader();
 
// Get the xml document object by sax reader.
Document document = reader.read("person.xml");
 

We will use the below xml file to read in this example

 
 
<?xml version="1.0" encoding="UTF-8"?>
<company name="mycompany" address="California" country="US">
      <person>
            <personid>000001</personid>
            <name>Bob</name>
            <age>29</age>
      </person>
      <person>
            <personid>000002</personid>
            <name>Sam</name>
            <age>34</age>
      </person>
      <person>
            <personid>000003</personid>
            <name>Susan</name>
            <age>22</age>
      </person>
</company>
 

The example of reading the xml file using dom4j is given below.

 
package com.java.dom4jexample;
 
import java.util.List;
 
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
 
public class XMLReadExample {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws DocumentException {
        // Create the SAXReader object
        SAXReader reader = new SAXReader();
        // Read XML as document
        Document document = reader.read("person.xml");
        // Define the xpath
        String xpathExpression = "//company/person";
        // Get the list of nodes on given xpath
        List<node> nodes = document.selectNodes(xpathExpression);
 
        // loop through the items
        for (Node node : nodes) {
            Node id = node.selectSingleNode("personid");
            System.out.println("Person Id : " + id.getText());
            Node name = node.selectSingleNode("name");
            System.out.println("Name : " + name.getText());
            Node age = node.selectSingleNode("age");
            System.out.println("Age : " + age.getText());
        }
    }
}
 
//output
 
Person Id : 000001
Name : Bob
Age : 29
Person Id : 000002
Name : Sam
Age : 34
Person Id : 000003
Name : Susan
Age : 22
 
 
 

Here is how to read attributes from elements:

 
        Element root = document.getRootElement();
        List<attribute> attributes = root.attributes();
        for (Attribute attribute : attributes) {
            System.out.println("Company " + attribute.getName() + " is " + attribute.getValue());
        }
//output
Company name is mycompany
Company address is California
Company country is US