【问题标题】:How to count child nodes of XML?如何计算 XML 的子节点?
【发布时间】:2012-09-15 06:46:53
【问题描述】:

我有一个这样的 XML ...

<?xml version="1.0"  encoding="iso-8859-1"?>
<world>
  <country> 
      <name> France </name>  
      <city> Paris </city>
      <population> 3996 </population>
      <city> Lille </city>
      <state>NE</state>
      <zip> 000000 </zip>
   </country>
</world>

在这里我们可以看到 Tag Country 有 6 个子节点。但是如何以编程方式计算它。 您的帮助将不胜感激.. 在此先感谢....

【问题讨论】:

  • 看我的回答,它会解决你的问题。

标签: android xml parsing


【解决方案1】:

使用下面的代码计算NodeList的子节点,它会解决你的问题。

URL url = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("country");
int i=nodeList.getLength();
System.out.println("Total Child is:- " + i);

有关使用 Dom Parser 进行 XML 解析的更多信息,请参见下面的链接。

XML Parsing Using DOM Parser

【讨论】:

    【解决方案2】:

    要获取集合的大小:

    nl.getLength() //n1 is the object of NodeList
    
    public int getLength()
    
    The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
    

    也可以看看NODELIST

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多