How to parse xml using different parent nodes in a

2019-03-05 05:11发布

问题:

In my xml file I have two or more parent nodes like:-

//parent node pizza //attributes are 1 Veg Pizza
//parent node burger
//attributes are 1 Veg Burger,

Whenever the user clicks on pizza listview item then the user should be able to view only list of pizza items in another activity's listview. I know how to call next activity and so on, but I want to know how I can use different parent nodes in my java class, exactly what are the changes I need to do in my java class, please see this link, I am using this tutorial, but here they are using only one parent node song but I want to add more and I have added in my xml file but don't know what are the changes I need to do in java class.

回答1:

carrier.xml ile contains below xml contents
<?xml version="1.0" encoding="utf-8"?>
<carrier>
    <vehicle>
        <vehicle
            cid="1"
            cname="TAXI" />
        <vehivle
            cid="0"
            cname="AUTO" />
   </vehicle>

// In your code 
XmlPullParser xpp=null;
int eventType = 0;
XmlPullParserFactory factory =null;
BufferedReader bufr=null;   
StringBuilder total ="";
     try{           
    bufr = new BufferedReader(new FileReader("/carrier.xml"));
    total = new StringBuilder();
    String line=""; 
    while ((line = bufr.readLine()) != null)
    {     
    total.append(line);
    }                       
    factory = XmlPullParserFactory.newInstance();  
    factory.setNamespaceAware(true);   
    xpp = factory.newPullParser();   
    xpp.setInput(new StringReader(new String(total)));                  
    eventType = xpp.getEventType();             
    }catch(XmlPullParserException e){
    // Log.v("xmlpullparser"," "+e);
    e.printStackTrace();
    }catch(IOException ie){
    // Log.v("IOException"," "+ie);
    ie.printStackTrace();
    }


    try{
    while (eventType != XmlPullParser.END_DOCUMENT){                    
    if(eventType == XmlPullParser.START_TAG){ 
    String Scid="",Scname="";
    int acount=xpp.getAttributeCount();             
    if(acount!=-1){
    for(int x=0;x<acount;x++){                                              
                        if(xpp.getAttributeName(x).equalsIgnoreCase("cid")){
                            Scid=xpp.getAttributeValue(x);                                                                                  
                        }if(xpp.getAttributeName(x).equals("cname")){
                            Scname=xpp.getAttributeValue(x);
                        }
                    }               
    }   
    }       
    eventType = xpp.next();  
    }                               
    }catch(Exception e){        
            e.printStackTrace();
    }

After this you can use the Scid Scname etc in your code as per your convenience