我想用递归方法获取XML文件的最大深度,首先我声明变量
public static int maxdepth=0;
private static void GetDepth(NodeList nl, int level,int maxdepth) {
level++;
if (maxdepth<level)
{
maxdepth= level;
}
if(nl != null && nl.getLength() > 0){
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element)
{
GetDepth(n.getChildNodes(), level, maxdepth);
}
}
}
}
public static void main(String[] args) {
NodeList nl = root.getChildNodes();
GetDepth(nl,level,maxdepth);
System.out.println(maxdepth);
}
当我显示变量maxdepth的值时,我收到值0,作为声明
最佳答案
您可以使用XPath 2.0将其作为一行来完成:
max(for $n in //* return count($n/ancestor::*))
即使是在Java中,您也会使它变得比现在困难得多:
public int maxDepth(Node node) {
int max = 0;
NodeList kids = node.getChildNodes();
if (kids.getLength() == 0) {
return 0;
}
for (int i=0; i<kids.getLength(); i++) {
int kidMax = maxDepth(kids.item(i);
if (kidMax > max) max = kidMax;
}
return max + 1;
}
没有测试。
关于java - 递归方法最大深度-静态变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10336355/