【问题标题】:XPATH Query not return resultXPATH 查询不返回结果
【发布时间】:2010-02-24 15:52:41
【问题描述】:

您好,代码如下:

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?

【问题讨论】:

    标签: java xml xpath jaxp


    【解决方案1】:

    我一般不熟悉 Java,但我对 XPath 的怀疑是由于您的代码中缺少(对我来说很明显)命名空间处理。根据您的输入,该标记位于默认名称空间“http://www.w3.org/1999/xhtml”中,因此我希望您必须编写一些代码来告诉 Java XPath 设备有关此名称空间的信息。

    通过谷歌搜索发现这个有用的博客条目 XPath with namespaces in Java 在我看来它可以解决您的问题。

    【讨论】:

    • 谢谢丹!你是对的。这是一个命名空间问题。这篇博文解决了我的问题。
    • +1。这始终是一个命名空间问题…… XML 命名空间永远不会让人感到意外。显然,它们作为“我不需要关心的另一个属性”而被取消了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 2019-09-18
    • 2012-05-08
    相关资源
    最近更新 更多