Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中xPath结果的问题_Java_Dom_Sax - Fatal编程技术网

java中xPath结果的问题

java中xPath结果的问题,java,dom,sax,Java,Dom,Sax,我在理解下面代码的行为时遇到了问题,在我理解它之前,我很难修复它。我已经将问题隔离到了可以显示问题的最简单代码段: String sourceXML = "<root>\n" + "<Rule test=\"1\"/>\n" + "<Rule test=\"2\"/>\n" + "</root>"; DocumentBuilder db = DocumentBuild

我在理解下面代码的行为时遇到了问题,在我理解它之前,我很难修复它。我已经将问题隔离到了可以显示问题的最简单代码段:

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.....");
        }
    }
我的期望是,每次迭代中,每个xPath匹配只能是1,因为我正在对从源XML提取的每个元素运行xPath。我预期的结果是:

Number of Items found : 2
Found 1 matches to xpath.....
Found 1 matches to xpath.....
然而,当循环遍历nodelist(这是正确的,源代码中有2个)时,似乎每次都在整个源XML上运行xpath,尽管我认为我提取了每个节点,只是在该节点上运行xpath


有谁能帮助我理解我在这里做错了什么吗?

您将xpath求值放在了一个循环中,对吗?这就是你得到你得到的东西的原因吗?正确-它在循环中,正如我希望它在我迭代的节点列表中的每个节点上求值一样,但它似乎不是那样工作的。这是因为//规则是一条绝对路径。。。它基本上保证了评估将从xml文档的根开始。。。尝试使用。/@test。。。看看会发生什么。。。
Number of Items found : 2
Found 1 matches to xpath.....
Found 1 matches to xpath.....