【发布时间】:2013-12-21 09:36:01
【问题描述】:
我对 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
它必须是带有名称空间的东西或标题中的任何其他东西,因为没有它它可以生成一些输出。我不知道我做错了什么。
【问题讨论】:
-
“它必须是带有命名空间的东西” - 正确。我链接到的“可能重复”问题是谷歌给我的“jdom xpath 命名空间”的第一个命中
-
现在似乎已解决 - 更改:命名空间 namespace = Namespace.getNamespace("my","w3.org/1999/xhtml"); 和 XPathExpression
xp = xpfac.compile("//my:a[@ class= 'nextpage']", Filters.element(),null,namespace); -
这个问题似乎离题了,因为它现在已经解决了(请参阅 OP 的评论)。
-
您应该将该评论转化为答案(SO 让您可以回答自己的问题)并将答案标记为已接受,以便其他人可以看到问题已解决。
-
由于此代码使用 JDOM 2.x 并且指示的重复使用 JDOM1.x(它们在处理 XPath 的方式上非常不同),所以这不是重复...