带有XML命名空间的XPath - 未解决命名空间上下文

时间:2017-02-28 11:28:02

标签: java xpath

我想通过XPath查询XML。此XML具有声明的命名空间。我已经读过必须设置XPath对象上的NameContext并且应该启用文档工厂中的命名空间感知。

但getNamespaceURI(#String)方法中的输出永远不会打印。我做错了什么?

String xpathStr = ... //some string

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.parse(settlementFile);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath(),
xpath.setNamespaceContext(new NamespaceContext() {

     public String getNamespaceURI(String prefix) {
        System.out.println("I'm here");      
        ... //do some work 
    }

    public String getPrefix(String uri) {
        throw new UnsupportedOperationException();
    }

    public Iterator getPrefixes(String uri) {
        throw new UnsupportedOperationException();
    }
});

XPathExpression xpathExpression = xpath.compile(xpathStr);
String result = xpathExpression.evaluate(document);

0 个答案:

没有答案