0

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);
    }
}
}
4

2 回答 2

1

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]
于 2010-07-24T21:19:54.783 回答
1

XPath 表达式所针对的 XML 文档:

//stp:handler[2]

被评估,没有默认或声明的命名空间,所有节点都在“无命名空间”中。命名空间中没有任何节点"http://service.mine.org/dgs"。除非您在实际情况中使用另一个 XML 文档,否则上述表达式不得选择任何节点——这正是您得到的。

如果您正在使用一个您没有显示的文档,它确实有一个默认命名空间,那么您很可能在 Java 代码中拼错了命名空间。

此外,请尝试使用 XPath 表达式的这种变体(带或不带命名空间前缀):

(//stp:handler)[2]

于 2010-07-24T22:22:39.067 回答