【问题标题】:count xml nodes under specific node计算特定节点下的 xml 节点
【发布时间】:2011-08-29 09:09:03
【问题描述】:
<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 下有多少个端口。

【问题讨论】:

    标签: java xml


    【解决方案1】:

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

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

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

    【讨论】:

    【解决方案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);
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      这个呢?

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

      【讨论】:

      • NodeList listOfShelfs = doc.getElementsByTagName("shelfs"); int slot1_count = ((Element)(listOfShelfs.item(0))).getElementsByTagName("port").getLength(); System.out.println(slot1_count);谢谢...
      • System.out.println?这是Java命令,你不是说console.log(slot1_count)或document.write(slot1_count)
      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多