简体   繁体   中英

Recursive method doesn't work - ArrayList<String>

I have a problem with a recursive method , that put all element of an XML File in an ArrayList

<?xml version="1.0"  encoding="iso-8859-1"?>
<country>
  <name> France </name>
  <city> Paris </city>
  <region>
     <name> Nord-Pas De Calais </name>
     <population> 3996 </population>
     <city> Lille </city>
  </region>
  <region>
     <name> Valle du Rhone </name>
     <city> Lyon </city>
     <city> Valence </city>
  </region>
 </country>

But my function does'nt complete all round (Get all element) : the result is [country, name, city, region, region] but i want to get all element [country, name, city, region,name,population,region,name,city,city], i think that the recursively call is not in the right place, this is my code

public static ArrayList<String> TreeToArray (Node node)
{
    ArrayList<String> ArrayNoeud = new ArrayList<String> ();

   ArrayNoeud.add(node.getNodeName());


    NodeList nl = node.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
      Node n = nl.item(i);

      if (n instanceof Element)
      {
           ArrayNoeud.add(n.getNodeName());

      }

    TreeToArray(n);
    }


    return ArrayNoeud;  



}

You are recursing but then you are not assigning the return value to anything.

instead of

 TreeToArray(n);

try this:

 ArrayNoeud.addAll( TreeToArray(n) );

You are throwing the recursion result without using it. you should add something like this:

ArrayNoeud.addAll(TreeToArray(n)); // Didn't notice it was java :) AddRange is C#

Also, you variable name should start with a lowercase.

It's always weird to see an English French composite word (not Complaining) :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM