Query XML Document with XPath and JDOM

We can use XPath to query an XML Document, searching for specific nodes using a query syntax. This tutorial shows how to Query an XML Document with XPath and JDOM.

Maven Dependencies

You need to add the following dependencies to your classpath to run the examples below. The default implementation for JDOM2 is jaxen.

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>
<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.6</version>
</dependency>

Suppose we have the following xml document, we can query specific information.

  • select all elements
  • select all attributes of elements
  • select the nth element
  • select element with attribute
<?xml version="1.0" encoding="UTF-8"?>
<courses>
    <course id="1">
        <name>Query XML with XPath and JDOM</name>
        <price>0.0</price>
    </course>
    <course id="2">
        <name>XPath and JDOM</name>
        <price>0.0</price>
    </course>
    <course id="3">
        <name>
            <![CDATA[
               characters & ? $ ^ with markup
            ]]>
        </name>
        <price>12.0</price>
    </course>
</courses>

XPath with JDOM

First we parse and load the XML Document into memory. Next, we create an XPathFactory. Using this facotry, we compile the XPath Expression. We can either call the evaluate to return a list when we are expecting multiple elements/attributes or call the evaluateFirst to only return the first element/attribute.

package com.memorynotfound.xml.jdom;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;

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

public class QueryXmlXPath {

    public static void main(String... args) throws JDOMException, IOException {

        // parse and load file into memory
        InputStream in = QueryXmlXPath.class.getResourceAsStream("/example.xml");
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(in);

        // create xpath factory
        XPathFactory xpath = XPathFactory.instance();

        System.out.println("1. select all elements");
        XPathExpression<Element> expr = xpath.compile("//course/name", Filters.element());
        List<Element> courses = expr.evaluate(document);
        for (Element course : courses){
            System.out.println("   " + course.getValue().trim());
        }

        System.out.println("\n2. select all attributes of element");
        XPathExpression<Attribute> attrExpr = xpath.compile("[email protected]", Filters.attribute());
        List<Attribute> ids = attrExpr.evaluate(document);
        for (Attribute id : ids){
            System.out.println("   " + id.getValue());
        }

        System.out.println("\n3. select the second element");
        expr = xpath.compile("//course[2]/name", Filters.element());
        Element name = expr.evaluateFirst(document);
        System.out.println("   " + name.getValue());

        System.out.println("\n4. select element by xpath with attribute");
        expr = xpath.compile("//course[@id='1']/name", Filters.element());
        Element child = expr.evaluateFirst(document);
        System.out.println("   " + child.getValue());
    }
}

Output:

1. select all elements
   Query XML with XPath and JDOM
   XPath and JDOM
   characters & ? $ ^ with markup

2. select all attributes of element
   1
   2
   3

3. select the second element
   XPath and JDOM

4. select element by xpath with attribute
   Query XML with XPath and JDOM

References

Download

You may also like...