dom4j中的XPath评估从org.w3c.dom.Document创建的文档无法按预期工作

时间:2013-07-19 17:34:58

标签: java xml dom4j

我正在尝试使用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;
}

1 个答案:

答案 0 :(得分:3)

按如下方式更改xml加载:

DocumentBuilderFactory docBuilderFactor = DocumentBuilderFactory.newInstance();
docBuilderFactor.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();