2012-12-07 78 views
0

我使用的是DOM解析器解析XML,但我似乎已經遇到一個問題,我已經結構類似於以下XML數據:XML解析問題(多標籤)

<Bookings> 
    <BookingNo>12345678</BookingNo> 
    <Pickup> 
    <AddressLine>Line 1</AddressLine> 
    <AddressLine>Line 2</AddressLine> 
    <AddressLine>Line 3</AddressLine> 
    <AddressLine>Line 4</AddressLine> 
    <AddressLine>Line 5</AddressLine> 
    <Postcode> 
     <PostcodeOut>pstOut</PostcodeOut> 
     <PostcodeIn>pstIn</PostcodeIn> 
    </Postcode> 
    <AddressCoords> 
     <Latitude>1.12345670</Latitude> 
     <Longitude>-1.1234567890</Longitude> 
    </AddressCoords> 
    </Pickup> 
    <Destination> 
    <AddressLine>Line 1</AddressLine> 
    <AddressLine>Line 2</AddressLine> 
    <AddressLine>Line 3</AddressLine> 
    <Postcode> 
     <PostcodeOut>pstOut</PostcodeOut> 
     <PostcodeIn>pstIn</PostcodeIn> 
    </Postcode> 
    <AddressCoords> 
     <Latitude>1.1234567890</Latitude> 
     <Longitude>-1.1234567890</Longitude> 
    </AddressCoords> 
    </Destination> 
    <PickupTime>DateTime</PickupTime> 
    <DestinationTime>DateTime</DestinationTime> 
    <VehicleType>Car</VehicleType> 
    <NumberOfPassengers>1</NumberOfPassengers> 
    <Passengers> 
    <PassengerName>Name</PassengerName> 
    <PassengerContactNo>123456</PassengerContactNo> 
    </Passengers> 
    <Mileage>2</Mileage> 
</Bookings> 

問題我得到的是我需要從pickupdestination得到AddressLine,但他們需要分開,與我現有的代碼,我分別拉他們,但我只拉第一行(第1行)都是。我使用的解析器XML代碼:

public class XMLParser { 

    // constructor 
    public XMLParser() { 

    } 

    /** 
    * Getting XML from URL making HTTP request 
    * @param url string 
    * */ 
    public String getXmlFromUrl(String url) { 
     String xml = null; 

     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 



      xml = EntityUtils.toString(httpEntity); 
      InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8")); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sbtwo = new StringBuilder(); 
      String myfeed = null; 
      while ((myfeed = reader.readLine()) != null) { 
       final String newjsontwo = myfeed.replaceAll(
         "throw 'allowIllegalResourceCall is false.';", ""); 
       sbtwo.append(newjsontwo); 
      } 
      is.close(); 


     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     // return XML 
     return xml; 
    } 

    /** 
    * Getting XML DOM element 
    * @param XML string 
    * */ 
    public Document getDomElement(String xml){ 
     Document doc = null; 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     try { 

      DocumentBuilder db = dbf.newDocumentBuilder(); 

      InputSource is = new InputSource(); 
       is.setCharacterStream(new StringReader(xml)); 
       doc = db.parse(is); 

      } catch (ParserConfigurationException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } catch (SAXException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } catch (IOException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } 

      return doc; 
    } 

    /** Getting node value 
     * @param elem element 
     */ 
    public final String getElementValue(Node elem) { 
     Node child; 
     if(elem != null){ 
      if (elem.hasChildNodes()){ 
       for(child = elem.getFirstChild(); child != null; child = child.getNextSibling()){ 
        if(child.getNodeType() == Node.TEXT_NODE ){ 

         return child.getNodeValue(); 
        } 
       } 
      } 
     } 
     return ""; 
    } 

    /** 
     * Getting node value 
     * @param Element node 
     * @param key string 
     * */ 
    public String getValue(Element item, String str) {  
      NodeList n = item.getElementsByTagName(str);   
      return this.getElementValue(n.item(0)); 
     } 

,我的主要活動中的代碼是:

XMLParser parser = new XMLParser(); 
        Document doc = parser.getDomElement(xml); // getting DOM 
        references = new ArrayList<String>(); 
        NodeList nl = doc.getElementsByTagName("Bookings"); 
        NodeList nlpickup = doc.getElementsByTagName("Pickup"); 
        NodeList nldestination = doc 
          .getElementsByTagName("Destination"); 
        AddressData = new StringBuilder(); 

        // looping through all item nodes <item> 
        for (int i = 0; i < nl.getLength(); i++) { 
         HashMap<String, String> map = new HashMap<String, String>(); 

         Element e = (Element) nl.item(i); 
         resultCode = parser.getValue(e, "BookingNo"); 
         Pickup = parser.getValue(e, "Pickup"); 
         DateTime = parser.getValue(e, "PickupTime"); 

         Element etwo = (Element) nlpickup.item(i); 

         PAddressTwo = parser.getValue(etwo, "AddressLine"); 

         // System.out.println("/// "+ AddressData); 
         // System.out.println("/////"+parser.getValue(etwo, 
         // "AddressLine")); 

         PPostIn = parser.getValue(etwo, "PostcodeOut"); 
         PPostOut = parser.getValue(etwo, "PostcodeIn"); 

         Element ethree = (Element) nldestination.item(i); 
         DAddressOne = parser.getValue(ethree, "AddressLine"); 
         DPostIn = parser.getValue(ethree, "PostcodeOut"); 
         DPostOut = parser.getValue(ethree, "PostcodeIn"); 

         splitDate(); 

         map.put("BookNo", resultCode); 
         map.put("Datetime", TimeFinal + " on " + DateFinal); 
         map.put("PickupAddress", PAddressTwo + " " + PPostIn 
           + " " + PPostOut); 
         map.put("DestinationAddress", DAddressOne + " " 
           + DPostIn + " " + DPostOut); 

         references.add(resultCode); 

         mylist.add(map); 
        } 

        adapter = new SimpleAdapter(
          MyJourney.this, 
          mylist, 
          R.layout.myjourneys_item, 
          new String[] { "BookNo", "Datetime", 
            "PickupAddress", "DestinationAddress" }, 
          new int[] { R.id.journeysRefText, 
            R.id.journeysDateText, 
            R.id.journeysFromText, R.id.journeysToText }); 

       } 

我要去哪裏錯了?

我知道有一種叫做SAX解析器的東西,但我可以找到一個匹配我所尋找的示例。

回答

0

試試這個:皮卡和目標

Element element = document.getDocumentElement(); 

    // For Pickup 
    NodeList nodeListPickup = element.getElementsByTagName("Pickup"); 
    for (int i = 0; i < nodeListPickup.getLength(); i++) { 
     Node node = nodeListPickup.item(i); 
     NodeList pickUp = node.getChildNodes(); 

     for (int j = 0; j < pickUp.getLength(); j++) { 

      Node nodePickup = pickUp.item(j); 
      String name = nodePickup.getNodeName(); 

      if(name.equals("AddressLine")){ 
       System.out.println("Pickup > AddressLine > " +nodePickup.getFirstChild().getNodeValue()); 
      }  
     } 
    } 

    // For Destination 
    NodeList nodeListDestination = element.getElementsByTagName("Destination"); 
    for (int i = 0; i < nodeListDestination.getLength(); i++) { 
     Node node = nodeListDestination.item(i); 
     NodeList destination = node.getChildNodes();     
     for (int j = 0; j < destination.getLength(); j++) { 

      Node nodeDestination = destination.item(j);  
      String name = nodeDestination.getNodeName(); 

      if(name.equals("AddressLine")){     
       System.out.println("Destination > AddressLine > " +nodeDestination.getFirstChild().getNodeValue()); 
      }  
     } 
    } 

我已經創建了不同的節點列表,你可以得到內標籤的休息之內的兩次,目前我只顯示了AddressLine。讓我知道這是否有幫助。

+0

這確實有很大幫助,只需要弄清楚如何正確構建它現在大聲笑 –