0

我正在尝试制作一个简单的 foreach-sortof 循环。Android中似乎不存在foreach,但是我对如何解决这个问题一无所知...

我正在尝试打印出一个信息块,并且在每个块上都有新信息..一个简单的循环......

这是我到目前为止想出的:

while (eventType != XmlPullParser.END_DOCUMENT) {

                    String[] separated_nodes = node.split(":");


if(eventType == XmlPullParser.START_TAG && xpp.getName().equalsIgnoreCase(tag)) {
    if(tag.equals("ChannelPackage")) {

                         // ArtNr:Name:Price:Period:InitDisPeriod:DisPeriod

                         // text.setText("Network "+xpp.getAttributeValue(null, "Name"));

                             packagename += xpp.getAttributeValue(null, separated_nodes[1].trim());   
                             artnr += xpp.getAttributeValue(null, separated_nodes[0].trim());                         
                             price += xpp.getAttributeValue(null, separated_nodes[2].trim());                         
                             period += xpp.getAttributeValue(null, separated_nodes[3].trim());                        
                             initdisperiod += xpp.getAttributeValue(null, separated_nodes[4].trim());                        
                             disperiod += xpp.getAttributeValue(null, separated_nodes[5].trim());


                             text.setText("Channel Packages: \n" + artnr +"\n" +
                                        "Package Name: "+ packagename + "\n" +
                                        "Price : "+ price +"\n" +
                                        "Period: "+ period +"\n" +
                                        "InitDisPeriod: "+ initdisperiod +"\n" +
                                        "DisPeriod: "+ disperiod +"\n"
                                        );


                         text.setMovementMethod(new ScrollingMovementMethod());

                     }

                 } else if(eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase(tag)) {
                         System.out.println("End tag "+xpp.getName());


                 } 
                 eventType = xpp.next();
                }

               // text.setText(nodes.toString());
            }catch(Exception ex){
                text.setText("Failed!");
                Log.i("HTTPResponse", ex.toString());
            }

但结果是这样的:

  • 艺人
  • 艺人
  • 艺人
  • 包裹名字
  • 包裹名字
  • 包裹名字

但我想要 :

  • 艺人
  • 包裹名字
  • 艺人
  • 包裹名字

如何格式化我的代码以获得该结果?我完全一无所知:/

4

1 回答 1

2

If the object you're iterating over extends Collection of type T you can do a foreach loop like this

for(T obj : someCollection) {
    // do something
}

EDIT:

Ok, it seems to me that the question isn't really about the foreach loop (I don't think you can use int whith this parser) but that you're getting the elements from your xml in the wrong order. Maybe you should consider using nextTag() instead of next()?

于 2012-10-15T12:11:47.737 回答