我正在尝试解析 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”。
我究竟做错了什么?