1

我正在使用 JTidy 来解析网页数据。我的问题如下:

可以在以前检索到的节点上调用 XPath.evalate 方法吗?

我会更好地解释。通常您使用xmlPath.evaluate(pattern, document, XPathConstants.NODE)方法调用来检索与您的 xpath 表达式匹配的节点列表。

一旦我检索到一个节点或 nodeList,我该如何从上一个检索到的节点开始执行 xmlPath.evaluate ,类似于 xmlPath.evaluate(pattern, node , XPathConstants.NODE)

4

1 回答 1

2

是的,我认为这是可能的:

URL url = new URL("http://www.w3.org");

// configure JTidy
Tidy tidy = new Tidy();
tidy.setXHTML(true);
tidy.setQuiet(true);
tidy.setXmlOut(true);
tidy.setShowWarnings(false);

Document doc = tidy.parseDOM(url.openConnection().getInputStream(), null);
XPath xpath = XPathFactory.newInstance().newXPath();

XPathExpression expr =
xpath.compile("//form[@action = 'http://www.w3.org/Help/search']");

Node form = (Node) expr.evaluate(doc, XPathConstants.NODE);

// create relative XPath    
expr = xpath.compile("ul/li[@class = 'last-item']/a");
Node lastItem = (Node) expr.evaluate(form, XPathConstants.NODE);

System.out.println(lastItem.getFirstChild().getNodeValue());

回报:

About W3C
于 2011-05-31T16:52:03.377 回答