gpt4 book ai didi

java - jdom2 XPath 查询的结果不明确

转载 作者:太空宇宙 更新时间:2023-11-04 15:17:53 28 4
gpt4 key购买 nike

我的 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

它必须是带有 namespace 或 header 中其他任何内容的内容,因为没有它它可以生成一些输出。我不知道我做错了什么。

最佳答案

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

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

A QName in the node test is expanded into an expanded-name using the namespace declarations from the expression context. This is the same way expansion is done for element type names in start and end-tags except that the default namespace declared with xmlns is not used: if the QName does not have a prefix, then the namespace URI is null (this is the same way attribute names are expanded). It is an error if the QName has a prefix for which there is no namespace declaration in the expression context.

实际上,这意味着只要 XML 文档中有“默认”命名空间,在 XPath 表达式中使用该命名空间时仍然需要为该命名空间添加前缀。 XPathFactory.compile(...) 方法暗示了这一要求 in the JavaDoc ,但并没有应有的那么清晰。您使用的前缀是任意的,并且仅适用于该 XPath 表达式。在您的情况下,代码将类似于(假设我们为 URI http://www.w3.org/1999/xhtml 选择命名空间 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"));
}

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

关于java - jdom2 XPath 查询的结果不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20717560/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com