4
嗨給出下面的代碼:XPath查詢不返回結果
private void extractLink(ScriptFile file) throws SAXException, IOException,
ParserConfigurationException, XPathExpressionException {
Document d = this.parseFile(file);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expr = xpath.compile("//link");
Object result = expr.evaluate(d, XPathConstants.NODE);
Node node = (Node) result;
if(result!=null)
{
this.log.debug("Links found: "+node.toString());
}
else
{
this.log.debug("No link found!");
}
}
private Document parseFile(ScriptFile file) throws SAXException, IOException, ParserConfigurationException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setNamespaceAware(true);
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(false);
dbf.setExpandEntityReferences(false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder db = dbf.newDocumentBuilder();
return db.parse(new ByteArrayInputStream(file.getFile()));
}
而且像輸入:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>Default-Config-Accounts</title>
</head>
<body>
</body>
</html>
爲什麼我的查詢返回NULL?
謝謝丹!你是對的。這是一個命名空間問題。博客文章解決了我的問題。 – er4z0r 2010-02-24 17:09:40
+1。它始終是一個命名空間問題...... XML命名空間永遠不會令人驚訝。顯然,他們被淘汰爲「我不需要關心的另一個屬性」。 – Tomalak 2010-02-26 12:42:39