2013-03-19 49 views
0

我想要做的只是從XML文件中讀取一行。我似乎不能得到任何東西,但空。我想直接從文檔中讀取會話ID,而無需創建大量代碼。必須有一個超級簡單的方法。如何使用解析xml android

<loginResponse> 
    <status message="Success" code="Success"/> 
    <sessionid>d713868c-608b-440f-a708-5b7055e2e8d2</sessionid> 
</loginResponse> 


  HttpResponse response = httpclient.execute(httppost); 
      HttpEntity r_entity = response.getEntity(); 
      String xmlString = EntityUtils.toString(r_entity); 
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder db = factory.newDocumentBuilder(); 
      InputSource inStream = new InputSource(); 
      inStream.setCharacterStream(new StringReader(xmlString)); 
      Document doc = db.parse(inStream); 


      doc.getDocumentElement().normalize(); 
      NodeList nodeLst = doc.getElementsByTagName("sessionid"); 
      Node node = nodeLst.item(0); 
      String sessionID = node.getTextContent(); 

      mDbHelper.createAccount(userName, password, sessionID); 

回答

1

最簡單的方式做,這是使用掃描儀類。

Scanner scan = new Scanner(stream); 
while (scan.hasNextLine()) { 
    String line = scan.nextLine(); 
    if(line.startsWith("\t<sessionid>")) 
    { 
     System.out.println(line.substring("\t<sessionid>".length())); 
    } 
}