2

我正在尝试解析 openweathermap api http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml。我通过 XmlPullParserFactory.newPullParser() 使用 KXmlParser,但 XMLPullParser.getName() 总是返回 null。这可能是一些愚蠢的错误,但似乎我可能需要你的帮助才能看到它。

这是通过HTTPURLConnection.

 URL url = new URL(urlString);
                URLConnection urlConnection = url.openConnection();
                HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();
                if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                    inputStream = httpConnection.getInputStream();
                }

我用了

BufferedReader buffer = new BufferedReader(
                            new InputStreamReader(inputStream));
                    String s="";
                    while ((s=buffer.readLine())!=null){
                        stringBuffer.append(s);
                        System.out.println(s);
                    }

以确保我正在成功读取 xml,结果证明代码运行正常。接下来,我使用下面的代码解析xml

XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
            XmlPullParser myparser = xmlFactoryObject.newPullParser();

            myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
                    , false);
            myparser.setInput(inputStream, null);

            int event = myparser.getEventType();

            while (event != XmlPullParser.END_DOCUMENT){
                Log.d("XMLPullParserHandler", "sdfdsf " + myparser.getName());
                String name = myparser.getName();

但我在 myparser.getName(); 处得到 java.lang.NullPointerException;上面的日志也显示“sdfdsf null”。

我究竟做错了什么?

4

2 回答 2

2

您可以解析给定的 xml 或将模式更改为 json 并解析 json

你的 xml 标签看起来像

<city id="2643743" name="London"> 
// tag name is city
// id and name are attributes with values 2643743 and London

注意:我只展示了几个标签的解析。但它应该可以帮助您理解并自己解析其余部分。

从文档

public abstract String getName () 在 API 级别 1 中添加

对于 START_TAG 或 END_TAG 事件,启用命名空间时返回当前元素的(本地)名称。禁用命名空间处理时,将返回原始名称。对于 ENTITY_REF 事件,返回实体名称。如果当前事件不是 START_TAG、END_TAG 或 ENTITY_REF,则返回 null。

解析 xml 并获取值

public class XMLPullParserHandler {



    public XMLPullParserHandler() {

    }
    public Void parse(InputStream is) {
        XmlPullParserFactory factory = null;
        XmlPullParser parser = null;
        try {
            factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            parser = factory.newPullParser();

            parser.setInput(is, null);
            boolean check =false;

           //factory instantiates an object

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {

                switch (eventType) {
                case XmlPullParser.START_TAG:

                    String tagname = parser.getName();
                    Log.i("Tag names are ",tagname);

                    if (tagname.equalsIgnoreCase("city")) {

                        if(parser.getAttributeValue(null, "id").equals("264374"))
                        {
                             String cityname= parser.getAttributeValue(null, "name");
                             Log.i(" City Name is ",cityname);
                        }

                    }
                    if (tagname.equalsIgnoreCase("coord")) {

                             String lat= parser.getAttributeValue(null, "lat");
                             String lon= parser.getAttributeValue(null, "lon");
                             Log.i("Latitude and Longitude is","Lat= "+lat+"Lon= "+lon);

                    }
                    if (tagname.equalsIgnoreCase("sun")) {

                     String rise= parser.getAttributeValue(null, "rise");
                     String set= parser.getAttributeValue(null, "set");
                     Log.i("Sun Rise and Sun set is","Rise= "+rise+"Set= "+set);

               }

                    break;

                case XmlPullParser.TEXT:
                    break;

                case XmlPullParser.END_TAG:


                    break;

                default:
                    break;
                }
                eventType = parser.next();
            }

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

日志

08-18 16:14:35.885: I/City Name is(31634): London
08-18 16:14:35.885: I/Latitude and Longitude is(31634): Lat= 51.51Lon= -0.13
08-18 16:14:35.885: I/Sun Rise and Sun set is(31634): Rise= 2014-08-18T04:51:39Set= 2014-08-18T19:16:53

此外,如果您的 xml 标记如下所示

<cityname type="test">City is London</cityname> 

获取价值

case XmlPullParser.TEXT:
       text = parser.getText();
break;

case XmlPullParser.END_TAG:
       if (tagname.equalsIgnoreCase("cityname")) {                             
        Log.i("Name is",text);
       }
break;

编辑:

异步任务

class TheTask extends AsyncTask<Void,Void,Void>
{

@Override
protected Void doInBackground(Void... params) {
    // TODO Auto-generated method stub
    String response;
       try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml");

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

            InputStream is = new ByteArrayInputStream(response.getBytes(Charset.forName("UTF-8")));
            new XMLPullParserHandler().parse(is); 

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    return null;
}   
}
于 2014-08-18T10:46:10.997 回答
1

START_DOCUMENT是您总是从解析器获得的第一个事件,而仅在,和事件getName()的情况下返回不为空。START_TAGEND_TAGENTITY_REF

对于 START_TAG 或 END_TAG 事件,启用命名空间时返回当前元素的(本地)名称。禁用命名空间处理时,将返回原始名称。对于 ENTITY_REF 事件,返回实体名称。如果当前事件不是 START_TAG、END_TAG 或 ENTITY_REF,则返回 null。

尝试这个:

while (event != XmlPullParser.END_DOCUMENT) {
    if (event == XmlPullParser.START_TAG || event == XmlPullParser.END_TAG) {
        Log.d("XMLPullParserHandler", "sdfdsf " + myparser.getName());
        String name = myparser.getName();
    }
    event = myparser.next();
}
于 2014-08-18T10:52:39.653 回答