[英]Java Xpath expression
我有以下XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://research.sun.com/wadl/2006/10">
<doc xmlns:jersey="http://jersey.dev.java.net/"
jersey:generatedBy="Jersey: 1.0.2 02/11/2009 07:45 PM"/>
<resources base="http://localhost:8080/stock/">
<resource path="categories"> (<<---I want to get here)
<method id="getCategoriesResource" name="GET">
而且我想获取resource/@path
的值,所以我有以下Java代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
// get the xml to parse from URI
Document doc = builder.parse(serviceUri + "application.wadl");
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
XPathExpression expression =
xpath.compile("/application/resources/resource/@path");
this.baseUri = (String) expression.evaluate(doc, XPathConstants.STRING);
使用此XPath表达式,结果( baseUri
)始终是空字符串( ""
)。
节点不在空字符串名称空间中,您必须指定它: /wadl:application/wadl:resources/wadl:resource/@path
。 另外,您应该在XPath引擎名称空间上下文中注册名称空间。
这是工作示例:
xpath.setNamespaceContext(new NamespaceContext()
{
@Override
public String getNamespaceURI(final String prefix)
{
if(prefix.equals("wadl"))
return "http://research.sun.com/wadl/2006/10";
else
return null;
}
@Override
public String getPrefix(final String namespaceURI)
{
throw new UnsupportedOperationException();
}
@Override
public Iterator getPrefixes(final String namespaceURI)
{
throw new UnsupportedOperationException();
}
});
XPathExpression expression = xpath.compile("/wadl:application/wadl:resources/wadl:resource/@path");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.