Java XML – JDOM2 – XPath

Xpath is a query language specification that is used to query an XML path. It provides a language that helps in retrieving specific nodes of an XML document using a query syntax. This tutorial does not explain XPath and assumes that the user is aware of XPath. What we explain here is how to use Xpath to query a JDOM2 document. The default implementation for JDOM2 is jaxen. To run the below examples jaxen needs to be in the classpath. To query the JDOM2 document first compile an XPathExpression using an XPathFactory. Use the expression to then evaluate the JDOM2 document.

package com.studytrails.xml.jdom;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
public class XPathExample2 {
    private static String xmlSource = "";
    public static void main(String[] args) throws JDOMException, IOException {
        // read the XML into a JDOM2 document.
        SAXBuilder jdomBuilder = new SAXBuilder();
        Document jdomDocument =;
        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());
        // select all links
        XPathExpression<Element> expr = xFactory.compile("//link", Filters.element());
        List<Element> links = expr.evaluate(jdomDocument);
        for (Element linkElement : links) {
        // select all links in image element
        expr = xFactory.compile("//image/link", Filters.element());
        List<Element> links2 = expr.evaluate(jdomDocument);
        for (Element linkElement : links2) {
        // get the media namespace
        Namespace media = jdomDocument.getRootElement().getNamespace("media");
        // find all thumbnail elements from the media namespace where the
        // attribute widht has a value > 60
        expr = xFactory.compile("//media:thumbnail[@width>60.00]", Filters.element(), null, media);
        // find the first element in the document and get its attribute named 'url'
        // find the child element of channel whose name is title. find the
        // descendant of item with name title.
        Element firstTitle = xFactory.compile("//channel/child::item/descendant::title", Filters.element()).evaluateFirst(jdomDocument);

Leave a Comment