如何从 xml in android 的相同键名中获取值

how to get values from same keyname from xml in android

我做了一个演示来解析 android 中的 xml 响应,我试过了并且一切顺利,但我不知道如何从 [= 中获取具有相同键名的相同参数的值24=] 回复,我的样本 xml 如下,

<NightlyRatesPerRoom size="8">
<NightlyRate baseRate="315.68" rate="315.68" promo="false"/>
<NightlyRate baseRate="229.33" rate="229.33" promo="false"/>
<NightlyRate baseRate="248.52" rate="248.52" promo="false"/>
<NightlyRate baseRate="267.71" rate="267.71" promo="false"/>
<NightlyRate baseRate="267.71" rate="267.71" promo="false"/>
<NightlyRate baseRate="248.52" rate="248.52" promo="false"/>
<NightlyRate baseRate="286.9" rate="286.9" promo="false"/>
<NightlyRate baseRate="286.9" rate="286.9" promo="false"/>
</NightlyRatesPerRoom>

我的代码

package com.amar.travelonwards.parser;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

import com.amar.travelonwards.model.RssFeed_RoomInfo;
import com.amar.travelonwards.utility.Consts;
import com.amar.travelonwards.utility.HotelBookingDetailsHandler;

public class NewsFeedParser_RoomInfo {
    private InputStream urlStream;
    private XmlPullParserFactory factory;
    private XmlPullParser parser;

    private List<RssFeed_RoomInfo> rssFeedList_Room;

    private RssFeed_RoomInfo rssFeed_room;

    public List<String> room_info;
    public List<String> bed_info;
    public List<String> commissionList;
    public List<String> surchargeList;
    public List<String> totalChargeList;
    public List<String> cancellation;
    public List<String> urlList;

    ArrayList<String> al;
    private String urlString;
    private String tagName;

    private String roomTypeDescription;
    private String bedTypeDesc;

    private String commissionableUsdTotal;
    private String surchargeTotal;
    private String total;
    private String averageRate;

    private String cancellationPolicy;
    private String url;

    private String rateCode;
    private String roomTypeCode;
    private String supplierType;
    private String bedType;
    private String smokePref;

    private String rateKey;

    public List<String> values;

    public List<String> list_rateCode;
    public List<String> list_roomTypeCode;
    public List<String> list_supplierType;
    public List<String> list_bedType;
    public List<String> list_smokePref;
    public List<String> list_rateKey;

    public List<String> total_addValue_list;

    /*
     * String temp[]; int i;
     */

    public List<List<String>> addValueList;
    int i = 0;
    public static final String ITEM = "HotelRoomResponse";
    public static final String CHANNEL = "ns2:HotelRoomAvailabilityResponse";

    public static final String HOTEL_NAME = "roomTypeDescription";
    public static final String ROOM_DESC = "BedType";

    public static final String ROOM_CHARGE = "ChargeableRateInfo";
    public static final String CANCELLATION = "cancellationPolicy";

    public static final String URL = "url";

    public static final String HOTEL_ID = "hotelId";
    public static final String ARRIVAL_DATE = "arrivalDate";
    public static final String DEPARTURE_DATE = "departureDate";
    public static final String RATE_CODE = "rateCode";
    public static final String ROOM_TYPE_CODE = "roomTypeCode";
    public static final String SUPPLIER_TYPE = "supplierType";
    public static final String BED_TYPE = "BedType";
    public static final String SMOKE_PREF = "smokingPreferences";
    public static final String RATE_KEY = "rateKey";

    public static final String VALUE_ADDS = "ValueAdds";
    public static final String VALUE_ADD = "ValueAdd";

    public HotelBookingDetailsHandler bookingDetailsHandler;

    public NewsFeedParser_RoomInfo(String urlString) {
        this.urlString = urlString;
    }

    public NewsFeedParser_RoomInfo() {
        // TODO Auto-generated constructor stub
    }

    public static InputStream downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // conn.setDoOutput(true);

        conn.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
        conn.setRequestProperty("Accept-Charset",
                "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

        conn.connect();

        int rCode = conn.getResponseCode();

        System.out.println("************Responce Code:************" + rCode);

        InputStream stream = conn.getInputStream();

        if (conn.getResponseCode() != 200) {
            stream = conn.getErrorStream();
            System.out.println("**********************OK**************");
        } else {
            stream = conn.getInputStream();
        }

        return stream;
    }

    public List<RssFeed_RoomInfo> parse() {
        try {
            int count = 0;
            factory = XmlPullParserFactory.newInstance();
            parser = factory.newPullParser();
            urlStream = downloadUrl(urlString);
            parser.setInput(urlStream, null);
            int eventType = parser.getEventType();
            boolean done = false;
            rssFeed_room = new RssFeed_RoomInfo();

            room_info = new ArrayList<String>();
            bed_info = new ArrayList<String>();

            commissionList = new ArrayList<String>();
            surchargeList = new ArrayList<String>();
            totalChargeList = new ArrayList<String>();
            cancellation = new ArrayList<String>();
            urlList = new ArrayList<String>();

            addValueList = new ArrayList<List<String>>();
            total_addValue_list = new ArrayList<String>();

            list_rateCode = new ArrayList<String>();
            list_roomTypeCode = new ArrayList<String>();
            list_supplierType = new ArrayList<String>();
            list_bedType = new ArrayList<String>();
            list_smokePref = new ArrayList<String>();
            list_rateKey = new ArrayList<String>();

            rssFeedList_Room = new ArrayList<RssFeed_RoomInfo>();
            while (eventType != XmlPullParser.END_DOCUMENT && !done) {
                tagName = parser.getName();
                // System.out.println("City Tag:"+tagName);
                switch (eventType) {
                case XmlPullParser.START_DOCUMENT:

                    break;
                case XmlPullParser.START_TAG:

                    if (tagName.equals(ITEM)) {

                        rssFeed_room = new RssFeed_RoomInfo();
                        values = new ArrayList<String>();
                    }
                    if (tagName.equals(RATE_CODE)) {
                        rateCode = parser.nextText().toString();

                        System.out.println("PArsed rateCode:" + rateCode);
                        list_rateCode.add(rateCode);
                    }
                    if (tagName.equals(ROOM_TYPE_CODE)) {
                        roomTypeCode = parser.nextText().toString();

                        System.out.println("PArsed roomtypecode:"
                                + roomTypeCode);
                        list_roomTypeCode.add(roomTypeCode);
                    }
                    if (tagName.equals(SUPPLIER_TYPE)) {
                        supplierType = parser.nextText().toString();

                        System.out.println("PArsed supplierType:"
                                + supplierType);
                        list_supplierType.add(supplierType);
                    }
                    if (tagName.equals(BED_TYPE)) {
                        bedType = parser.getAttributeValue(null, "id");

                        System.out.println("PArsed bedType:" + bedType);
                        list_bedType.add(bedType);
                    }
                    if (tagName.equals(SMOKE_PREF)) {
                        smokePref = parser.nextText().toString();

                        System.out.println("PArsed smokePref:" + smokePref);
                        list_smokePref.add(smokePref);
                    }
                    if (tagName.equals(RATE_KEY)) {
                        rateKey = parser.nextText().toString();

                        System.out.println("PArsed rateKey:" + rateKey);
                        list_rateKey.add(rateKey);
                    }
                    //

                    if (tagName.equals(HOTEL_NAME)) {
                        roomTypeDescription = parser.nextText().toString();

                        System.out.println("PArsed roomTypeDescription:"
                                + roomTypeDescription);
                        room_info.add(roomTypeDescription);
                    }
                    if (tagName.equals(ROOM_DESC)) {
                        parser.nextTag();
                        parser.require(XmlPullParser.START_TAG, "",
                                "description");
                        bedTypeDesc = parser.nextText();
                        parser.require(XmlPullParser.END_TAG, "", "description");
                        bed_info.add(bedTypeDesc);
                        System.out.println("PArsed bedTypeDesc:" + bedTypeDesc);

                    }
                    if (tagName.equals(ROOM_CHARGE)) {
                        commissionableUsdTotal = parser.getAttributeValue(null,
                                "commissionableUsdTotal");
                        commissionList.add(commissionableUsdTotal);
                        System.out
                                .println("Parse commission commissionableUsdTotal:"
                                        + commissionableUsdTotal);

                        surchargeTotal = parser.getAttributeValue(null,
                                "surchargeTotal");
                        surchargeList.add(surchargeTotal);
                        System.out.println("Parse surcharged surchargeTotal:"
                                + surchargeTotal);

                        total = parser.getAttributeValue(null, "total");
                        totalChargeList.add(total);
                        System.out.println("Parsed total:" + total);

                        averageRate = parser.getAttributeValue(null,
                                "averageRate");
                        System.out.println("Print avgNight:" + averageRate);
                        System.out.println("PArsed commissionableUsdTotal:"
                                + commissionableUsdTotal);
                    }

                     if (tagName.equalsIgnoreCase("NightlyRatesPerRoom")) {
                            System.out.println("<NightlyRatesPerRoom>");
                             al  = new ArrayList<String>(); // if its root tag, arraylist begins here 
                        }

                        if (tagName.equalsIgnoreCase("NightlyRate")) {
                            System.out.print("<NightlyRate>");
                            String rateValue = parser.getAttributeValue(null, "rate");
                            System.out.print("Rate is : " + rateValue);
                            al.add(rateValue); // adds the value i.e rate to al
                        }
                    if (tagName.equals(CANCELLATION)) {
                        cancellationPolicy = parser.nextText().toString();
                        System.out.println("PArsed cancellationPolicy:"
                                + cancellationPolicy);
                        cancellation.add(cancellationPolicy);
                    }

                    if (tagName.equals(VALUE_ADD)) {

                        parser.nextTag();
                        parser.require(XmlPullParser.START_TAG, "",
                                "description");
                        values.add(parser.nextText());
                        parser.require(XmlPullParser.END_TAG, "", "description");

                    }
                    if (tagName.equals(URL)) {
                        url = parser.nextText().toString();
                        System.out.println("PArsed url:" + url);
                        urlList.add(url);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if (tagName.equals(CHANNEL)) {
                        done = true;

                    } else if (tagName.equals(ITEM)) {

                        rssFeed_room = new RssFeed_RoomInfo(
                                roomTypeDescription, bedTypeDesc,
                                commissionableUsdTotal, surchargeTotal, total,
                                averageRate, cancellationPolicy, url, rateCode,
                                roomTypeCode, supplierType, bedType, smokePref,
                                rateKey);
                        Consts.roomSelectionList.clear();
                        HashMap<String, String> roomMap = new HashMap<>();

                        roomMap.put("roomTypeDescription", roomTypeDescription);
                        roomMap.put("bedTypeDesc", bedTypeDesc);
                        roomMap.put("commissionableUsdTotal",
                                commissionableUsdTotal);
                        roomMap.put("surchargeTotal", surchargeTotal);
                        roomMap.put("total", total);
                        roomMap.put("averageRate", averageRate);
                        roomMap.put("cancellationPolicy", cancellationPolicy);
                        roomMap.put("url", url);
                        roomMap.put("rateCode", rateCode);
                        roomMap.put("roomTypeCode", roomTypeCode);

                        roomMap.put("supplierType", supplierType);
                        roomMap.put("bedType", bedType);
                        roomMap.put("smokePref", smokePref);
                        roomMap.put("rateKey", rateKey);
                        Consts.roomSelectionList.add(roomMap);
                        rssFeedList_Room.add(rssFeed_room);

                        addValueList.add(values);

                        System.out.println("AddValues:::" + addValueList);

                    }

                    break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rssFeedList_Room;
    }
}

我想获取 arrayList 中 "rate" 的所有值,谁能帮我解决这个问题,在此先感谢。

很简单。对于 xml 解析,我使用了 xmlpullparser。你可以试试这个代码。

演示 class

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

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

public class Demo {

    public static void main(String[] args) throws XmlPullParserException, IOException
    {
      try {

         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
         ArrayList<String> al = null; // ArrayList initialized here
         XmlPullParser xpp = factory.newPullParser();
         File xmlFile = new File("test.xml");
         FileInputStream fis = new FileInputStream(xmlFile);
         xpp.setInput(fis, null);
         xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
         int eventType=xpp.getEventType();

         while(eventType!=XmlPullParser.END_DOCUMENT){
             String tagname = xpp.getName();                 
                 switch (eventType) {

                case XmlPullParser.START_TAG:   

                    if (tagname.equalsIgnoreCase("NightlyRatesPerRoom")) {
                        System.out.println("<NightlyRatesPerRoom>");
                        al = new ArrayList<String>(); // if its root tag, arraylist begins here 
                    }

                    if (tagname.equalsIgnoreCase("NightlyRate")) {
                        System.out.print("<NightlyRate>");
                        String rateValue = xpp.getAttributeValue(null, "rate");
                        System.out.print("Rate is : " + rateValue);
                        al.add(rateValue); // adds the value i.e rate to al
                    }

                    break;

                case XmlPullParser.END_TAG:

                    if (tagname.equalsIgnoreCase("NightlyRatesPerRoom")) {
                        System.out.println("</NightlyRatesPerRoom>");
                    }


                    if (tagname.equalsIgnoreCase("NightlyRate")) {                      
                        System.out.println("</NightlyRate>");                       
                    }

                default:
                    break;

            }

             eventType=xpp.next();
         }

       System.out.println("**** ArrayList Values Starts printing ****");

         for (int i = 0; i < al.size(); i++) {

             System.out.println("Rate : " +al.get(i));

        } // end of for loop

     } // end of try 

          catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace(); 
            }

    } // end of main function

} // end of class

输出:

<NightlyRatesPerRoom>
<NightlyRate>Rate is : 315.68</NightlyRate>
<NightlyRate>Rate is : 229.33</NightlyRate>
<NightlyRate>Rate is : 248.52</NightlyRate>
<NightlyRate>Rate is : 267.71</NightlyRate>
<NightlyRate>Rate is : 267.71</NightlyRate>
<NightlyRate>Rate is : 248.52</NightlyRate>
<NightlyRate>Rate is : 286.9</NightlyRate>
<NightlyRate>Rate is : 286.9</NightlyRate>
</NightlyRatesPerRoom>
**** ArrayList Values Starts printing ****
Rate : 315.68
Rate : 229.33
Rate : 248.52
Rate : 267.71
Rate : 267.71
Rate : 248.52
Rate : 286.9
Rate : 286.9

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<NightlyRatesPerRoom size="8">
<NightlyRate baseRate="315.68" rate="315.68" promo="false"/>
<NightlyRate baseRate="229.33" rate="229.33" promo="false"/>
<NightlyRate baseRate="248.52" rate="248.52" promo="false"/>
<NightlyRate baseRate="267.71" rate="267.71" promo="false"/>
<NightlyRate baseRate="267.71" rate="267.71" promo="false"/>
<NightlyRate baseRate="248.52" rate="248.52" promo="false"/>
<NightlyRate baseRate="286.9" rate="286.9" promo="false"/>
<NightlyRate baseRate="286.9" rate="286.9" promo="false"/>
</NightlyRatesPerRoom>      

注意:要使用xmlpullparser,您需要download this library并将其添加到您的项目中。

要在 android 中工作,您只需复制并粘贴 Try 中的工作代码,然后将其粘贴到您的 class 中。希望对您有所帮助!

是的,我的 way.here 得到了答案,它是:

if (tagName.equals(NightlyRate)) {
                        night_rate = parser.getAttributeValue(null, "rate");
                        rates.add(night_rate);
                        System.out.println("MY_NIGHT_RATE " + rates.toString());

                    }