1

Web ページのデータを解析するために JTidy を使用しています。私の質問は次のとおりです。

以前に取得したノードで XPath.evalate メソッドを呼び出すことは可能ですか?

もっとよく説明します。通常、xmlPath.evaluate(pattern, document, XPathConstants.NODE)メソッド呼び出しを使用して、xpath 式に一致するノードのリストを取得します。

nodeまたは nodeListを取得したら、 xmlPath.evaluate(pattern, node , XPathConstants.NODE)に似た 、以前に取得したnodeから開始して xmlPath.evaluate を実行するにはどうすればよいですか?

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 に答える