Java中的Xpath筛选器仅重新带回第一个值结果

时间:2018-12-11 10:07:39

标签: java xml xpath filter

我是新来的,简短点说,我有这个问题。 我想获取具有属性“ @ name ='Priority'的Child's的所有值作为列表,然后我将其删除:

    XPathExpression expr = xpath.compile ("//*[@name='Priority']");
        NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
         System.out.println("Found " + nl.getLength() );
            for(int i = 0; i < nl.getLength(); i++) {
                System.out.println("Priority:" + xpath.compile("//*[@name='Priority']").evaluate(nl.item(i)));
                System.out.println("==================");
            }

我的XML结构在这里

  <INSTANCE id="obj.43200" class="Car" name="Car-43200">
        <ATTRIBUTE name="Position" type="STRING">NODE x:15.5cm y:7cm w:1.5cm h:1cm index:69</ATTRIBUTE>
        <ATTRIBUTE name="External tool coupling" type="STRING" />
        <ATTRIBUTE name="Direction" type="ENUMERATION">Horizontal</ATTRIBUTE>
        <ATTRIBUTE name="Priority" type="INTEGER">40</ATTRIBUTE>
     </INSTANCE>

但是当我在Eclipse中执行Java代码时,我得到了:

    Found 9
Priority:40
==================
Priority:40
==================
Priority:40
==================
Priority:40
==================
Priority:40
==================
Priority:40
==================
Priority:40
==================
Priority:40
==================
Priority:40
==================

对于所有其他8个XPath过滤器结果,它仅带给我第一个结果作为最终结果。 对于exmp应该是这样的:

     Found 2
Priority:40
==================
Priority:5

以此类推...

我该怎么办?在此先感谢:)

1 个答案:

答案 0 :(得分:0)

基于给定的xml内容和java代码,输出如下

Found 1
Priority:40
==================

我对您的xml内容一无所知。请尝试这个

XPathExpression expr = xpath.compile ("//*[@name='Priority']");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println("Found " + nl.getLength() );
for(int i = 0; i < nl.getLength(); i++) {
    System.out.println("Priority:" + nl.item(i).getTextContent());
    System.out.println("==================");
}