从url获取xml不起作用

时间:2014-04-08 20:37:24

标签: java android

public class GetXMLTask extends AsyncTask<String, Void, String> {

// XML node names
static final String NODE_EVEN = "event";
static final String NODE_NAME = "name";
static final String NODE_DATE = "date";
static final String NODE_LOC = "location";

private TextView txtView; 



public GetXMLTask(TextView txtView) {
   this.txtView = txtView; 

}

@Override
protected String doInBackground(String... urls) {
    String xml = null;
    for (String url : urls) {
        xml = getXmlFromUrl(url);

    }
    return xml;
}

@Override
protected void onPostExecute(String xml) {

    XMLDOMParser parser = new XMLDOMParser();
    InputStream stream = new ByteArrayInputStream(xml.getBytes());
    Document doc = parser.getDocument(stream);

    NodeList nodeList = doc.getElementsByTagName(NODE_EVEN);

    ArrayList<Event>events = new ArrayList<Event>();

    Event event = new Event();
    for (int i = 0; i < nodeList.getLength(); i++) {
       // event = new Event();
        Element e = (Element) nodeList.item(i);

        //will use for something later on
        event.setName(parser.getValue(e, NODE_NAME));
        //event.setName(parser.getValue(e, NODE_DATE));
        event.setName(parser.getValue(e, NODE_LOC));            
        events.add(event);
    }
    txtView.setText(doc.toString()); // to test xml!

}

/* uses HttpURLConnection to make Http request from Android to download
 the XML file */
private String getXmlFromUrl(String urlString) {
    StringBuffer output = new StringBuffer("");

    InputStream stream = null;
    URL url;
    try {
        url = new URL(urlString);
        URLConnection connection = url.openConnection();

        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        httpConnection.setRequestMethod("GET");
        httpConnection.connect();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            stream = httpConnection.getInputStream();
            BufferedReader buffer = new BufferedReader(
                    new InputStreamReader(stream));
            String s = "";
            while ((s = buffer.readLine()) != null)
                output.append(s);
        }
    } catch (MalformedURLException e) {
        Log.e("Error", "Unable to parse URL", e);
    } catch (IOException e) {
        Log.e("Error", "IO Exception", e);
    }

    return output.toString();


}


}

完成这一过程并不需要很长时间,因此考虑到模拟器有多慢,getxmlfromurl肯定会出错?我在textview中得到了输出

org.apache.harmony.xml.dom.DocumentImpl@b3d5c4b0

在调用getXMLFromUrl iv测试之前,我的网址很好。

1 个答案:

答案 0 :(得分:2)

没有什么是错的。您正在成功解析XML文档,您在doc变量中引用了该文档。

所有错误的是你期望Document.toString()会给你一些有意义的东西。看起来它没有被覆盖,这就是你获得该字符串的原因。如果要再次获取XML文本,则需要使用变换器IIRC。

您的getXmlFromUrl方法已被破坏,但它正在删除换行符,这意味着如果您有XML:

<foo>line 1
line 2</foo>

最终会出现单行内容“line 1line2”,这是不正确的。此外,如果不指定编码,则不应调用String.getBytes()。 (同上InputStreamReader没有编码。)基本上,不清楚为什么你不直接从HttpURLConnection的输入strema解析XML ...这将是更少的代码,并且可以避免你目前在代码中遇到的各种错误。