xPath的问题导致java

时间:2017-07-24 01:47:42

标签: java dom sax

我在理解下面代码的行为时遇到了问题,直到我明白了,我才难以解决它。我已将问题分离到最简单的代码片段,我可以显示问题:

String sourceXML = "<root>\n"
            + "<Rule test=\"1\"/>\n"
            + "<Rule test=\"2\"/>\n"
            + "</root>";

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(sourceXML));

    Document doc = db.parse(is);

    NodeList ruleList = doc.getElementsByTagName("Rule");
    System.out.println("Number of Items found : " + ruleList.getLength());

    for (int t = 0; t < ruleList.getLength(); t++) {
        if (ruleList.item(t).getNodeType() == Node.ELEMENT_NODE) {
            Element ruleElement = (Element) ruleList.item(t);
            String xPathToUse = "//Rule/@test";
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList ruleNodeList = (NodeList) xpath.evaluate(xPathToUse, ruleElement, XPathConstants.NODESET);
            System.out.println("Found " + ruleNodeList.getLength() + " matches to xpath.....");
        }
    }

生成以下输出:

Number of Items found : 2
Found 2 matches to xpath.....
Found 2 matches to xpath.....

我的期望是每次迭代的每个xPath匹配只有1,因为我在从源XML中提取的每个元素上运行xpath。我期望的输出是:

Number of Items found : 2
Found 1 matches to xpath.....
Found 1 matches to xpath.....

然而,似乎循环遍历节点列表(这是正确的 - 源中有2个),每次都在整个源XML上运行xpath,即使我认为我提取了每个节点而且是只需在那上面运行xpath。

有人能帮助我理解我在这里做错了吗?

0 个答案:

没有答案