计算特定节点下的xml节点

时间:2011-08-29 09:09:03

标签: java xml

<element>
  <slot name="slot1">
    <port status="active"/>
    <port status="inactive"/>
  </slot>
  <slot name="slot2">
    <port status="active"/>
  </slot>
</element>

NodeList listOfElement = doc.getElementsByTagName("port");这给出了xml文件中的端口总数。

我需要找出slot1下有多少个端口。

3 个答案:

答案 0 :(得分:4)

一种方法是使用xpath过滤掉结果列表:

XPath xpath = XPathFactory.newInstance().newXPath();            
NodeList list=(NodeList) xpath.evaluate("/element/slot[@name='slot1']/port",doc, XPathConstants.NODESET);

这将只计算名为'slot1'的插槽下的端口。

答案 1 :(得分:2)

您可以在Java SE中使用javax.xml.xpath库,并利用count函数:

import java.io.FileInputStream;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        XPath xp = XPathFactory.newInstance().newXPath();
        InputSource xml = new InputSource(new FileInputStream("input.xml"));
        double count = (Double) xp.evaluate("count(//slot[@name='slot1']/port)", xml, XPathConstants.NUMBER);
    }

}

答案 2 :(得分:1)

这是怎么回事?

var slot1 = doc.getElementsByName("slot1");
var slot1_count = slot1[0].getElementsByTagName("port").length;
相关问题