代码之家  ›  专栏  ›  技术社区  ›  er4z0r

xpath查询未返回结果

  •  4
  • er4z0r  · 技术社区  · 16 年前

    嗨,给出以下代码:

    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>
    

    为什么我的查询返回空值?

    1 回复  |  直到 16 年前
        1
  •  2
  •   Dan Blanchard    16 年前

    一般来说,我不熟悉Java,但是我的XPath猜疑是由于代码中缺少(明显的我)命名空间处理引起的。从您的输入中,标记位于默认命名空间中“ http://www.w3.org/1999/xhtml “所以,我希望您必须编写一些代码来告诉Java XPath设备关于这个命名空间。

    通过谷歌搜索找到了这个有用的博客条目 XPath with namespaces in Java 在我看来这能解决你的问题。

    推荐文章
    robyp7  ·  fo:表到html表-xslt
    11 年前