开发者

count xml nodes under specific node

<element>
  <slot name="slot1">
    <port status="active"/>
    <port status="i开发者_如何学Cnactive"/>
  </slot>
  <slot name="slot2">
    <port status="active"/>
  </slot>
</element>

NodeList listOfElement = doc.getElementsByTagName("port"); this gives total number of port in xml file.

I need to find out how many ports are under slot1.


One way is to use xpath to filter out the resulting list:

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

This will only count the ports that are under slot with name 'slot1'.


You could use the javax.xml.xpath libraries in Java SE, and leverage the count function:

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);
    }

}


what about this?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜