问题描述
我正在尝试使用 XPATH 解析带有命名空间的 xml 文档.我已经阅读了它应该如何完成.我也实现了 NamespaceContext.但是,我仍然没有得到这些值.我想我错过了一些简单的东西.
I am trying to parse an xml document with namespace using XPATH. I have read how it is supposed to be done. I have implemented NamespaceContext as well. But, I still am not getting the values. I think I am missing something simple.
我的 xml 输入是
<?xml version="1.0" encoding="UTF-8"?>
<ns1:customer xmlns:ns1="http://test/ns1">
<ns1:name>john</ns1:name>
</ns1:customer>
我的主文件是 TestXMLPath
My Main file is TestXMLPath
public static void main(String[] args) throws Exception {
String myInputXML = "src/testxmlpath/input-with-namespace.xml";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String expression ="/ns1:customer/ns1:name";
Document document = db.parse(new File(myInputXML)) ;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new SimpleNamespaceContextImpl());
String value = xpath.evaluate(expression,document);
System.out.println("value" + value);
}
我的 NamespaceContext 实现是
my NamespaceContext implementation is
public class SimpleNamespaceContextImpl implements NamespaceContext {
@Override
public String getNamespaceURI(String prefix) {
System.out.println("getNameSpace for prefix "+prefix);
if (prefix == null) {
throw new NullPointerException("Null prefix");
} else if ("ns1".equals(prefix)) {
return "http://test/ns1";
} else if ("xml".equals(prefix)) {
return XMLConstants.XML_NS_URI;
} else {
return XMLConstants.XML_NS_URI;
}
}
@Override
public String getPrefix(String namespaceURI) {
return "ns1";
}
@Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
}
我在调用方法时打印出来.这是输出.
I print out when a method gets called. Here is the output.
getNameSpace for prefix ns1
getNameSpace for prefix ns1
value
BUILD SUCCESSFUL
我不明白,为什么它不起作用??
I can't understand, why won't it work ??
任何帮助将不胜感激.
谢谢
推荐答案
对我来说效果很好.输出:
Works fine for me. Output:
getNameSpace for prefix ns1
getNameSpace for prefix ns1
valuejohn
您确定要加载正确的文档吗?我正在使用 Xerces 来构建文档并使用 Saxon 来评估 XPath.相关类的转储:
Are you sure you're loading the right document? I'm using Xerces to build the document and Saxon to evaluate the XPath. A dump of the relevant classes:
class com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl
class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl
class net.sf.saxon.xpath.XPathFactoryImpl
这篇关于使用带有 Java 类命名空间的 xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!