2013-12-13 81 views
0

我是Android開發新手,我使用新波士頓教程來指導我解析一些從API中檢索到的xml,但它似乎並不爲我工作,我認爲這個問題是某處的處理程序,在任何地方,這裏是我的代碼,我會從應用類培訓相關摘錄開始:試圖用SAXParser解析Android應用程序中的XML

String test = null; 
    try { 
     //Assign XML to test string 
     test = new DownloadTextTask().execute(params).get(); 

     SAXParserFactory spf = SAXParserFactory.newInstance(); 
     SAXParser sp = spf.newSAXParser(); 
     XMLReader xr = sp.getXMLReader(); 
     //create handler 
     HandlingXMLStuff doingWork = new HandlingXMLStuff(); 
     xr.setContentHandler(doingWork); 

     //parse xml 
     xr.parse(test); 

     //Assign parsed xml to string 
     String information = "this is the access token: " + doingWork.getInformation(); 

     //Output parsed XML 
     TextView myTextView = (TextView) findViewById(R.id.mytextview); 
     myTextView.setText(information); 

    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (SAXException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ParserConfigurationException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

現在這裏是處理:

XMLDataCollected info = new XMLDataCollected(); 
boolean isUser = false; 
boolean isToken = false; 

public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{ 
    if(localName.equals("user")){ 
     isUser = true; 
    }else if(localName.equals("access_token")){ 
     isToken = true; 
    } 

} 

public void characters (char ch[], int start, int length) 
{ 
    String str = null; 

    for (int i = start; i < start + length; i++) { 
     StringBuilder sb = new StringBuilder(str); 
     sb.append(ch[i]); 
     str = sb.toString(); 
    } 
    if (isUser){ 
     int u = Integer.parseInt(str); 
     info.setID(u); 
    } 
    else if(isToken){ 
     info.setToken(str); 
    } 
} 



public String getInformation() 
{ 
    return info.dataToString(); 
} 

XMLDataCollected類別:

public class XMLDataCollected { 
int userId = 0; 
String accessToken = null; 

public void setID(int i){ 
    userId = i; 
} 

public void setToken(String t){ 
    accessToken = t; 
} 


public int getUserId(){ 
    return userId; 
} 


public String dataToString(){ 
    return accessToken; 
} 

最後這裏是我試圖解析XML:

<xml> 
<user>1</user> 
<access_token>a5923jh34gdhei592jdyeo3jk2354323ji4</access_token> 
<status>Login Successful</status> 
</xml> 

任何幫助,任何人都可以給我用這將是非常apreciated

回答

1

我也跟着那個教程,但我也不明白爲什麼它不起作用。 我做了一些研究,並附帶了XmlPullParser,它非常易於使用,並且運行得非常好。下面是XmlPullParser的文檔:

http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

希望它能幫助!

+0

謝謝!前一陣子得到了這個排序,但忘記接受你的答案! – Matt