Andy
Andy

Reputation: 33

count xml nodes under specific node

<element>
  <slot name="slot1">
    <port status="active"/>
    <port status="inactive"/>
  </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.

Upvotes: 2

Views: 6452

Answers (3)

bdoughan
bdoughan

Reputation: 149017

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

}

Upvotes: 2

ivantod
ivantod

Reputation: 773

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'.

Upvotes: 4

Marek Sebera
Marek Sebera

Reputation: 40651

what about this?

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

Upvotes: 1

Related Questions