如何将此Xml解析为数组--Android

时间:2014-02-04 06:59:38

标签: android xml eclipse google-maps

嘿我正在尝试解析此网址:http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4 进入我的程序,现在只要我能收到en_res name_kana和lat和lng就足够了。我想把它们放在一个数组中,我可以用来创建一个“for循环”来将标记放在谷歌地图上(不同的.java文件)。 我怎么能这样做?真的很受欢迎。

代码:     公共类HandleXml {

    private String feldname[] = new String[10];     //Declaring arrays with the Size 10, the API offers 10 entries
    private String lat[] = new String[10];  
    private String lng[] = new String[10];  
    private String budget[] = new String[10];   

       public int x = 0;                            //Counter for the arrays
       public int f = 0;
       public int a = 0;
       public int n = 0;
       public int b = 0;

    private String urlString = null;                
    public volatile boolean parsingComplete = true;
       private XmlPullParserFactory xmlFactoryObject;

       public HandleXml(String url)                     //Log.e's are used for easier Debugging
       {Log.e("a","a");
          this.urlString = url;
       }
       public String[] getFeldName()                    //Methods returning the values from the XML to the MainActivity
       {Log.e("b","b");
           return feldname;
       }
       public String[] getLat()
       {Log.e("c","c");
           return lat;
       }
       public String[] getLng()
       {Log.e("d","d");
           return lng;
       }
       public String[] getBudget()
       {Log.e("e","e");
           return budget;
       }
       public void parseXMLAndStoreIt(XmlPullParser myParser)  throws XmlPullParserException, IOException       //See name
       {
              Log.e("f","f");
              int event;
              int num=0;
              String text=null;
              Log.e("g","g");

              try 
              {
                  Log.e("h","h");
                  event = myParser.getEventType();                      //Get Event-Type          

              //  for (int i = 0; i < 122; i++) 

                  while (event != XmlPullParser.END_DOCUMENT) 
                  {
                     Log.e(""+num,""+num);
                     Log.e("i","i");
                     String name=myParser.getName();

                    if (name != null)
                        {Log.e("iu"+name,name);}
                    Log.e("j","j");

                    switch (event)                                      //React to the different events
                    {

                       case XmlPullParser.START_TAG:
                       break;
                       case XmlPullParser.TEXT:
                       text = myParser.getText();
                       break;

                       case XmlPullParser.END_TAG:
                          if(name.equals("name_kana"))
                          {
                              Log.e("k","k");
                              feldname[f] = text;
                              Log.e("adf"+feldname[f], feldname[f]);
                              f++;

                          }
                          else if(name.equals("lat"))
                          {     
                              Log.e("l","l");
                              lat[a] = text;// myParser.getAttributeValue(null,"value");
                              Log.e("lat",lat[a]);
                              a++;
                          }
                          else if(name.equals("lng"))
                          {     
                              Log.e("m","m");
                              lng[n] = text;// myParser.getAttributeValue(null,"value");
                              Log.e("lng",lng[n]);
                              n++;
                          }
                          else if(name.equals("name"))
                          {     
                              Log.e("n","n");
                              budget[b] =text;// myParser.getAttributeValue(null,"value");
                              Log.e(budget[b],budget[b]);
                              b++;

                          }
                          else
                          {}
                          break;
                    }   

                    num++;
                    event = myParser.next();

                 }
                 Log.e("p","p");
                         parsingComplete = false;

              } catch (Exception e) {
                 //e.printStackTrace();
              }

           }

       public void fetchXML()
       {
              Thread thread = new Thread(new Runnable()
              {
                 @Override
                 public void run() 
                 {
                    try 
                    {
                       URL url = new URL(urlString);
                       HttpURLConnection conn = (HttpURLConnection) 
                       url.openConnection();                                        
                         conn.setReadTimeout(10000 /* milliseconds */);
                         conn.setConnectTimeout(15000 /* milliseconds */);
                         conn.setRequestMethod("GET");
                          conn.setDoInput(true);
                          conn.connect();
                    InputStream stream = conn.getInputStream();
                    xmlFactoryObject = XmlPullParserFactory.newInstance();
                    XmlPullParser myparser = xmlFactoryObject.newPullParser();

                    myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
                    , false);
                    myparser.setInput(stream, null);
                    parseXMLAndStoreIt(myparser);
                    stream.close();
                    } catch (Exception e) 
                    {
                       e.printStackTrace();
                    }
                }
            });

            thread.start(); 


           }

        }

这是在MainActivity中:

 public void open(View view)  
{

      obj = new HandleXml(url);

      obj.fetchXML();

      while(obj.parsingComplete);

      feldname = obj.getFeldName();

      budget = obj.getBudget();

      lat2 = obj.getLat();
      lng2 = obj.getLng();

      int min = feldname.length;                                        //Set min to lowest length of any Array
      if (min > budget.length)
      {min = budget.length;}
      if (min > lat2.length)
      {min = lat2.length;}
      if (min > lng2.length)
      {min = lng2.length;}
      String aus;
        Log.e("länge", aus = String.valueOf(feldname.length));          //Array Length is 10

      for(int x = 0; x < feldname.length; x++){                         //Reading the Content of the Array for debug purpose
         if (feldname[x] != null)
         { Log.e("feldname", feldname[x]);


         }}


      Log.e("wtgs"+budget.length,"wtgs"+budget.length);                 //Further content reading for the Log
      Log.e("wtgs"+lng2.length,"wtgs"+lng2.length);

      for (int i =0; i < min; i++ )                                     //Placing Markers with Array Contents
      {
      Log.e("6","6");
    //  feldname = obj.getFeldName();
      Log.e("7","7");
    //  
      lat4 = lat2[i];
      lng4 = lng2[i];
      lat3 = Float.parseFloat(lat4);
      lng3 = Float.parseFloat(lng4);

      Log.e("10","10");

  GoogleMap mMap;
      Log.e("11","11");
      mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1)).getMap();
      Log.e("12","12");
        mMap.addMarker(new MarkerOptions()
        .position(new LatLng(lat3, lng3))
        .title(feldname[i]+" "+budget[i]));  
      Log.e("13","13"); 
      }
}

更多信息,我的HandleXml类

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

logcat的

02-04 16:24:49.515: W/ActivityManager(2350): Unable to start service Intent { act=com.google.android.gms.analytics.service.START cmp=com.google.android.gms/.analytics.service.AnalyticsService (has extras) } U=0: not found
02-04 16:24:49.520: W/GAV2(30695): Thread[GAThread,5,main]: Service unavailable (code=1), will retry.
02-04 16:24:50.555: W/nalizableReferenceQueue(30903): Could not load Finalizer in its own class loader. Loading Finalizer in the current class loader instead. As a result, you will not be able to garbage collect this class loader. To support reclaiming this class loader, either resolve the underlying issue, or move Google Collections to your system class path.
02-04 16:24:50.555: W/nalizableReferenceQueue(30903): java.io.FileNotFoundException: com/google/inject/internal/util/$Finalizer.class
02-04 16:24:50.555: W/nalizableReferenceQueue(30903):   at com.google.inject.internal.util.$FinalizableReferenceQueue$DecoupledLoader.getBaseUrl(SourceFile:269)
02-04 16:24:50.555: W/nalizableReferenceQueue(30903):   at com.google.inject.internal.util.$FinalizableReferenceQueue$DecoupledLoader.loadFinalizer(SourceFile:253)
02-04 16:24:50.555: W/nalizableReferenceQueue(30903):   at com.google.inject.internal.util.$FinalizableReferenceQueue.loadFinalizer(SourceFile:175)
02-04 16:24:50.555: W/nalizableReferenceQueue(30903):   at com.google.inject.internal.util.$FinalizableReferenceQueue.<clinit>(SourceFile:100)
02-04 16:24:50.555: W/nalizableReferenceQueue(30903):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-04 16:24:50.555: W/nalizableReferenceQueue(30903):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-04 16:24:50.555: W/nalizableReferenceQueue(30903):   at dalvik.system.NativeStart.main(Native Method)
02-04 16:24:50.835: W/ActivityManager(2350): Permission denied: checkComponentPermission() owningUid=10044
02-04 16:24:50.835: W/ActivityManager(2350): Permission denied: checkComponentPermission() owningUid=10044
02-04 16:24:50.910: W/ActivityManager(2350): Permission denied: checkComponentPermission() owningUid=10044
02-04 16:24:50.910: W/ActivityManager(2350): Permission denied: checkComponentPermission() owningUid=10044
02-04 16:24:50.940: W/ActivityManager(2350): Permission denied: checkComponentPermission() owningUid=10044
02-04 16:24:50.945: W/ActivityManager(2350): Permission denied: checkComponentPermission() owningUid=10044

由于地图我必须在真实设备上调试一些部分,很多条目...但没有真正的错误关注程序

1 个答案:

答案 0 :(得分:0)

您可以先发出Http get请求以从网址获取数据。

然后使用任何xml解析器来解析标记并获取所需的数据。

对于解析,您可以使用XmlPullParser或您选择的解析器。解析后,可以将其添加到数组或arraylist

http://developer.android.com/training/basics/network-ops/xml.html

注意:所有网络操作都应该在后台线程中完成。

使用AsyncTaskThread。您还可以使用名为Volley的库。

编辑:

你的解析看起来很好。我试过你的代码。你可以有arraylist

ArrayList<String> nameList = new ArrayList<String>();  
ArrayList<String> budList = new ArrayList<String>(); 
ArrayList<String> latList = new ArrayList<String>(); 
ArrayList<String> lngList = new ArrayList<String>();

然后

public void parseXMLAndStoreIt(XmlPullParser myParser)  throws XmlPullParserException, IOException       //See name
    {
           Log.e("f","f");
           int event;
           int num=0;
           String text=null;
           Log.e("g","g");
           try 
           {
               Log.e("h","h");
               event = myParser.getEventType();                         
               //  for (int i = 0; i < 122; i++) 
               while (event != XmlPullParser.END_DOCUMENT) 
               {
                  // Log.e(""+num,""+num);
                  // Log.e("i","i");
                  String name=myParser.getName();

                 if (name != null)
                 {
                    // Log.e("iu"+name,name);
                 }
                 switch (event)                                    
                 {

                    case XmlPullParser.START_TAG:
                    break;
                    case XmlPullParser.TEXT:
                    text = myParser.getText();
                    break;

                    case XmlPullParser.END_TAG:
                      String lat =null,bud=null,lng=null,nam=null;;
                       if(name.equals("name_kana"))
                       {
                          budList.add(text);

                       }
                       else if(name.equals("lat"))
                       {     
                           latList.add(text);
                       }
                       else if(name.equals("lng"))
                       {     
                           lngList.add(text);
                       }
                       else if(name.equals("name"))
                       {     
                           nameList.add(text);
                       }
                       else
                       {

                       }


                       break;
                 }  

                 num++;
                 event = myParser.next();

               }  

           } catch (Exception e) {
              e.printStackTrace();
           }

        }