2012-09-18 60 views
0

這裏是SOAP響應:如何從SOAP響應中獲取xml元素的值? (安卓)

<?xml version="1.0" encoding="utf-8"?> 
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> 
    <soap12:Body> 
     <SearchResponse xmlns="..."> 
      <SearchResult> 
       <?xml version="1.0" standalone="yes"?> <items blahblahblah1 </items> 
       <?xml version="1.0" standalone="yes"?> <items blahblahblah2 </items> 
      </SearchResult> 
     </SearchResponse> 
     </soap12:Body> 
</soap12:Envelope> 

從「信息搜索結果」中,我想每一個「項目」一次一個完整個XML的。我的意思是,我想單獨獲得一整個「項目blahblahblah /物品」。我怎麼做?

這是我已經想出了使用DOM從「SearchResult」中獲取所有xml的內容,但是如何獲取項目?

DocumentBuilder db = factory.newDocumentBuilder(); 
InputSource inStream = new InputSource(); 
inStream.setCharacterStream(new StringReader(soapResponse)); 
Document doc = db.parse(inStream); 

NodeList nl = doc.getElementsByTagName("SearchResult"); 
xml = nl.item(0).getFirstChild().getNodeValue(); 
+1

不知道你使用的是什麼庫,但如果它只處理肥皂,那麼你可以另外使用Jsoup來解析內部xml。 – bdares

回答

3

一種方法是編寫一個通用函數來解析已知標記的XML。 {

public static String parseXMLForTag(String xml, String tag) { 
     try { 
      // Create XMLPullParserFactory & XMLPullParser 
      XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
      XmlPullParser parser = factory.newPullParser(); 
      parser.setInput(new StringReader(xml)); 

      // boolean to indicate desired tag has been found 
      boolean foundTag = false; 
      // variable to fill contents 
      StringBuilder tagContents = new StringBuilder(); 

      // loop over document 
      int eventType = parser.getEventType(); 
      while (eventType != XmlPullParser.END_DOCUMENT) { 
       switch (eventType) { 
       case XmlPullParser.START_TAG: 
        if (parser.getName().equals(tag)) { 
         // Found tag, start appending to tagContents 
         foundTag = true; 
        } else if (foundTag) { 
         // New start tag inside desired tag 
         tagContents.append("<" + parser.getName() + ">"); 
        } 
        break; 
       case XmlPullParser.END_TAG: 
        if (parser.getName().equals(tag)) { 
         // Finished gathering text for tag 
         return tagContents.toString(); 
        } else if (foundTag) { 
         // end tag inside desired tag 
         tagContents.append("</" + parser.getName() + ">"); 
        } 
        break; 
       case XmlPullParser.TEXT: 
        if (foundTag) { 
         // text inside desired tag 
         tagContents.append(parser.getText()); 
        } 
        break; 
       } 
       // Get next event type 
       eventType = parser.next(); 
      } 
      return null; 
     } catch (Exception e) { 
      return null; 
     } 
    } 
} 

然後,您可以使用此方法來拉出的搜索結果,即

String searchResult = parseXMLForTag(response, "SearchResult"); 

,並使用該結果來分析項目

String item = parseXMLForTag(searchResult, "item"); 

注意,此方法不優化任何方式,但它應該爲你的目的工作。