4

こんにちは、次のコードが与えられました:

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を返すのはなぜですか?

4

1 に答える 1

2

私は一般的にJavaに精通していませんが、XPathの疑いは、コード内の(私には明らかな)名前空間の処理の欠如によって引き起こされます。あなたの入力から、タグはデフォルトの名前空間 " http://www.w3.org/1999/xhtml " にあるので、この名前空間について Java XPath 装置に伝えるコードを書く必要があると思います。

少しグーグルすると、この便利なブログエントリXPath with namespaces in Javaが見つかります。これは、問題を解決するように見えます。

于 2010-02-24T16:10:30.473 に答える