Java Xpath 表达式 [英] Java Xpath expression
本文介绍了Java Xpath 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 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 代码:
And I want to get the value of resource/@path
so I have the following Java code:
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
) 始终为空字符串 (""
).
With this XPath expression the result (baseUri
) is always the empty string (""
).
推荐答案
节点不在空字符串命名空间中,必须指定:/wadl:application/wadl:resources/wadl:resource/@path代码>.此外,您应该在 XPath 引擎命名空间上下文中注册命名空间.
The nodes are not in the empty string namespace, you must specify it: /wadl:application/wadl:resources/wadl:resource/@path
. Also, you should register the namespace in the XPath engine namespace context.
这是工作示例:
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");
这篇关于Java Xpath 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文