0

再帰メソッドを使用して 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 を受け取ります。

4

3 に答える 3

4

int maxdepthのメソッドシグネチャでgetDepth、静的変数を非表示にしていますmaxdepth。署名から削除します。

private static void GetDepth(NodeList nl, int level)

その後、メソッドは機能します。

于 2012-04-26T15:19:05.037 に答える
2

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;
}

未検証。

于 2012-04-26T21:52:05.077 に答える
1

このコード部分で:

if (maxdepth<level)
{
    maxdepth= level;
}

静的変数ではなく、ローカル変数 maxdepth を更新しています。変数の 1 つに別の名前を付けると機能しますが、メソッドの maxdepth パラメータは不要なので削除します。

于 2012-04-26T15:29:12.037 に答える