我搜索了很多,但从来没有找到我想要的。
我想控制当前页面中是否存在 xpath。
我发现有 java/xml、php 等......但不仅仅是 java。
如果存在 xpath,我会搜索一种简单的方法来检查当前页面。
谢谢你。
问候。
你可以使用javax.xml.xpath.XPath.evalute
方法:
例子:
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
Node node = (Node) path.evaluate("//myXPath", document, XPathConstants.NODE);
if (node == null)
// don't exists
else
// I exist!
更新
怎么弄document
。
复制粘贴我的旧代码的一些行:
BufferedInputStream bufferPage = new BufferedInputStream(new URL("http://www.yourUrl.com").openStream());
Tidy tidy = new Tidy();
tidy.setQuiet(true);
tidy.setShowWarnings(false);
tidy.setInputEncoding("UTF-8");
Document document = tidy.parseDOM(bufferPage, null);
document.normalize();
我使用库(Tidy)来阅读 html 页面。
http://jtidy.sourceforge.net/download.html
http://jtidy.sourceforge.net/apidocs/index.html?org/w3c/tidy/package-tree.html
您可以使用该实用程序方法,该方法将返回 XPath 查询(无论是 XML 标记还是 XML 属性)的值(如果存在)。否则,它会抛出一个异常,您可以按照自己的方式处理:
public String getValue(String xpathQuery) throws Exception
{
Node node = null;
try
{
node = (Node) xPath.evaluate(xpathQuery, doc, XPathConstants.NODE);
if (node == null)
throw new Exception("Xpath query "+xpathQuery+" returned no results");
if (node.getNodeType() == Node.ATTRIBUTE_NODE)
return node.getNodeValue();
else
return node.getTextContent();
} catch (Exception e)
{
throw new Exception("Failed to get value from " + doc.getDocumentURI() + " using XPath expression: " + xpathQuery, e);
}
}
如果您使用 JAXP API,您可以使用返回 NODE-SET 的 XPath 表达式,然后在 Java 代码中检查返回的 NodeList 是否为空;或者您可以将结果类型指定为 BOOLEAN 在这种情况下您将直接获得布尔结果。