1

我正在尝试使用 dom4j 1.6.1 使用 XPath 遍历以下文档。我正在寻找<query>元素的数量。

<?xml version="1.0" encoding="UTF-8"?>
<reportLineageResponse>
   <querySet expressionLocale="en-us">
      <queries xmlns="http://developer.cognos.com/schemas/report/9.0/">
         <query name="Top 10 Sales Staff List"/>
         <query name="Top 10 Sales Staff by Quantity List"/>
         <query name="Sales Figures America Region Combination Chart"/>
      </queries>
   </querySet>
</reportLineageResponse>

这是调用 dom4j 的代码。

int numberOfQueries(org.w3c.dom.Document jaxpDocument) {
    DOMReader domReader = new DOMReader();
    org.dom4j.Document document = domReader.read(jaxpDocument);

    Map<String, String> nsMap = Collections.singletonMap("rep", "http://developer.cognos.com/schemas/report/9.0/");
    XPath queryXp = document.createXPath("/reportLineageResponse/querySet/rep:queries/rep:query")
    queryXp.setNamespaceURIs(nsMap);
    List<Node> queries = queryXp.selectNodes(document);
    return queries.size();
}

我正确指定了命名空间,但得到 0 个结果。可能是什么问题呢?


编辑:如果我在创建 dom4j.Document 后查看它,它的命名空间错误:

<?xml version="1.0" encoding="UTF-8"?>
<reportLineageResponse>
   <querySet expressionLocale="en-us">
      <queries xmlns="http://developer.cognos.com/schemas/report/9.0/">
         <query xmlns="" name="Top 10 Sales Staff List"/>
         <query xmlns="" name="Top 10 Sales Staff by Quantity List"/>
         <query xmlns="" name="Sales Figures America Region Combination Chart"/>
      </queries>
   </querySet>
</reportLineageResponse>

编辑:这是创建 org.w3c.dom.Document 的代码:

Document loadDocument(URL url) {
    InputStream stream = url.openStream();
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document result = docBuilder.parse(stream);
    stream.close();
    return result;
}
4

1 回答 1

3

更改您的 xml 加载,如下所示:

DocumentBuilderFactory docBuilderFactor = DocumentBuilderFactory.newInstance();
docBuilderFactor.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
于 2013-07-22T07:50:58.200 回答