我是Android开发的新手,我正在使用New Boston教程来指导我解析从API中检索到的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>


任何人都可以给我的帮助将非常可贵

最佳答案

我也遵循了该教程,但是我也不明白为什么它不起作用。
我进行了一些研究,并附带了XmlPullParser,它非常易于使用,并且效果很好。这是XmlPullParser的文档:

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

希望能帮助到你!

09-27 18:50