迭代器只返回1个值(XML导入)

时间:2017-05-10 14:16:17

标签: java xml iterator

我使用迭代器从XML文档中收集数据,但这并不能返回所需的所有数据。

//PROMOTION
    listImport = racine.getChildren("promo");
    i = listImport.iterator();
    while(i.hasNext()){
        Element courant = (Element)i.next();
        name = courant.getChildText("name");
        photo = courant.getChildText("photo");
        percentage = Double.valueOf(courant.getChildText("percentage"));
        authCustomer = Boolean.valueOf(courant.getChildText("authCustomerOnly"));
        //creation promotion
        promotions.add(new Promotion(name, percentage, authCustomer));
        int index = promotions.size()-1;
        //ajout authCustomer
        promotions.get(index).setAuthCustomer(authCustomer);
        //ajout recettes
        List<Element> listRecettes = courant.getChildren("recipes");
        Iterator<Element> i2 = listRecettes.iterator();
        while(i2.hasNext()){
            Element sousCourant = (Element)i2.next();
            if(sousCourant.getChildText("recipe") != null) promotions.get(index).addRecipe(sousCourant.getChildText("recipe")); //TODO Recettes perdues après import (1 seule reste)
            else System.err.println("recipe == null, "+"Iterator value : "+i2.toString());
            System.out.println(sousCourant.getChildText("recipe"));
        }
        //ajout %age
        promotions.get(index).setPercentage(percentage);
    }

我认为问题来自这里:

//ajout recettes
        List<Element> listRecettes = courant.getChildren("recipes");
        Iterator<Element> i2 = listRecettes.iterator();
        while(i2.hasNext()){
            Element sousCourant = (Element)i2.next();
            if(sousCourant.getChildText("recipe") != null) promotions.get(index).addRecipe(sousCourant.getChildText("recipe")); //TODO Recettes perdues après import (1 seule reste)
            else System.err.println("recipe == null, "+"Iterator value : "+i2.toString());
            System.out.println(sousCourant.getChildText("recipe"));
        }

原始XML文件:XML 1.0

导入后生成的XML:XML 2.0

1 个答案:

答案 0 :(得分:0)

您还需要将所有孩子标记为receipe,然后对其进行迭代

List<Element> listRecettes = courant.getChildren("recipes");
Iterator<Element> i2 = listRecettes.iterator();
while(i2.hasNext()){
  Element sousCourant = (Element)i2.next();

  // New code here
  List<Element> listrecipe = sousCourant.getChildren("recipe");
  Iterator<Element> i3 = listrecipe.iterator();
  while(i3.hasNext()){
    Element recipe = (Element)i3.next();
    promotions.get(index).addRecipe(recipe.getTextContent()); 

  }
}