您可以使用此和定製按烏爾需求...使用DOM解析器
公共類的測試{
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse("country.xml");
Element elem = dom.getDocumentElement();
int level = 1;
System.out.println(elem.getNodeName() + "--->" + level);
NodeList nl = elem.getChildNodes();
displayLevel(nl,level);
}
/**
* Recursive function to go through the nodes to display the level.
* @param nl
* @param level
*/
private static void displayLevel(NodeList nl, int level) {
level++;
if(nl != null && nl.getLength() > 0){
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
System.out.println(n.getNodeName() + "--->" + level);
displayLevel(n.getChildNodes(), level);
}
}else{
return;
}
}
}
那麼,什麼一直是你的方法這麼遠?你有什麼嘗試不起作用? – kaveman 2012-04-26 00:57:30
你想要的結果是什麼?找到文檔的最深處?或者只是一個通用的方法來計算嵌套的子節點的數量。根據我的經驗,節點深度通常並不重要,因爲它們通常是通過節點名稱找到的。 – botbot 2012-04-26 01:00:34