jdom2 XPath查询结果不明确

时间:2013-12-21 09:36:02

标签: java xpath jdom-2

我遇到jdom2 XPath的问题:

test.xhtml代码:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
<head>
<title>mypage</title>
</head>
<body>
<div class="in">
<a class="nextpage" href="url.html">
<img src="img/url.gif" alt="to url.html" />
</a>
</div>
</body>
</html>

Java代码:

Document document;
SAXBuilder saxBuilder = new SAXBuilder();

document = saxBuilder.build("test2.html");
XPathFactory xpfac = XPathFactory.instance();
XPathExpression<Element> xp = xpfac.compile("//a[@class = 'nextpage']", Filters.element());
for (Element att : xp.evaluate(document) ) {
  System.out.println("We have target " + att.getAttributeValue("href"));
}

但就这一点而言,我无法获得任何元素。我发现当查询为//*[@class = 'nextpage']时,它会找到它。

We have target url.html

它必须是带有命名空间或标题中任何其他内容的东西,因为没有它它可以生成一些输出。我不知道我做错了什么。

1 个答案:

答案 0 :(得分:0)

注意:虽然这与建议的副本中描述的问题相同,但其他问题与JDOM版本1.x有关。在JDOM 2.x中存在许多显着差异。这个答案与JDOM 2.x XPath实现which is significantly different有关。

XPath规范非常清楚如何在XPath表达式中处理名称空间。不幸的是,对于熟悉XML的人来说,命名空间的XPath处理与他们的期望略有不同。 This is the specification

  

使用表达式上下文中的名称空间声明,将节点测试中的QName扩展为扩展名。这与开始和结束标记中的元素类型名称进行扩展的方式相同,只是不使用使用xmlns声明的默认名称空间:如果QName没有前缀,则名称空间URI为null(这是相同的方式属性名称已扩展)。如果QName具有在表达式上下文中没有名称空间声明的前缀,则会出错。

实际上,这意味着,只要在XML文档中有“默认”命名空间,在XPath表达式中使用它时,仍然需要为该命名空间添加前缀。 XPathFactory.compile(...)方法提到了这个要求in the JavaDoc,但它并不像它应该的那样清晰。您使用的前缀是任意的,并且仅对该XPath表达式是本地的。在您的情况下,代码看起来像(假设我们为URI xhtml选择名称空间http://www.w3.org/1999/xhtml):

XPathFactory xpfac = XPathFactory.instance();
Namespace xhtml = Namespace.getNamespace("xhtml", "http://www.w3.org/1999/xhtml");
XPathExpression<Element> xp = xpfac.compile("//xhtml:a[@class = 'nextpage']", Filters.element(), null, xhtml);
for (Element att : xp.evaluate(document) ) {
    System.out.println("We have target " + att.getAttributeValue("href"));
}

我应该将其添加到常见问题解答中......谢谢。

相关问题