user5257774
user5257774

Reputation: 1

XPath using JDom

In my code below, I am trying to access my 'handler' XML elements using XPath, but I am having no luck - the 'elemHandler' element is always null. Can anyone share with me the obvious solution? Thanks in advance.

import java.io.IOException;
import java.io.StringReader;

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class XPathTest {
    private static String jobString = "<job name=\"Workflow.JOB\">" + 
                                           "  <handler name=\"xslt.converter\"/>" +
                                           "  <handler name=\"openoffice.renderer\">" +
                                           "    <opts input=\"ODS\" output=\"PDF\"/>" +
                                           "  </handler>" +
                                           "</job>";

    public static void main(String[] args) {
    try {
        Element elemJobInfo = new SAXBuilder().build(new StringReader(jobString)).detachRootElement();
        XPath handlerExpression = XPath.newInstance("//stp:handler[2]");
        handlerExpression.addNamespace("stp", "http://service.mine.org/dgs");
        Element elemHandler = (Element) handlerExpression.selectSingleNode(elemJobInfo);
        jobString = elemHandler.toString();
    }
    catch (IOException e) {
        System.out.println("Failure: " + e);
    }
    catch (JDOMException e) {
        System.out.println("Failure: " + e);
    }
    catch (Exception e) {
        System.out.println("Failure: " + e);
    }
}
}

Upvotes: 0

Views: 1893

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243579

The XML document against which the XPath expression:

//stp:handler[2]

is evaluated, has no default or declared namespaces and all nodes are in "no namespace". There isn't any node in the "http://service.mine.org/dgs" namespace. Unless you are using another XML document in your actual case, the above expression must not select any node -- and this is exactly what you get.

In case you are using a document that you haven't shown, that really has a default namespace, the chances are you have misspelt the namespace in your Java code.

Also, do try this variation of your XPath expression (with or without the namespace prefix):

(//stp:handler)[2]

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 362037

What's up with the stp namespace? The XML in jobString doesn't reference any namespaces. Have you tried it without the prefix?

//handler[2]

Upvotes: 1

Related Questions