<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;
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论