如何计算XML的子节点?

时间:2012-09-15 06:46:54

标签: android xml parsing

我有一个像这样的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个子节点。但是如何以编程方式计算它。 您的帮助将不胜感激.. 在此先感谢....

2 个答案:

答案 0 :(得分:0)

获取集合的大小:

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

答案 1 :(得分:0)

使用以下代码来计算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

相关问题