0

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

4

2 回答 2

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 解析的更多信息,请参见下面的链接。

使用 DOM 解析器进行 XML 解析

于 2012-09-15T07:04:15.667 回答
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

于 2012-09-15T06:57:41.437 回答