我正在尝试解析openweathermap api http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml
。我通过XmlPullParserFactory.newPullParser()使用KXmlParser,但XMLPullParser.getName()总是返回null。这可能是一个愚蠢的错误,但似乎我可能需要你的帮助来发现它。
下面是通过HTTPURLConnection
读取api的代码。
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();
但我得到java.lang.NullPointerException在myparser.getName();此外,上面的日志显示"sdfdsf null"。
我做错了什么?
您可以解析给定的xml或将模式更改为json并解析json
你的xml标签看起来像
<city id="2643743" name="London">
// tag name is city
// id and name are attributes with values 2643743 and London
注意:我只展示了几个标签的解析。但它应该可以帮助您理解并自己对其余部分进行解析。
来自文档
公共抽象字符串getName ()新增API level 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;
编辑:Asynctask
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;
}
}
START_DOCUMENT
是您总是从解析器获得的第一个事件,而getName()
仅在START_TAG
, END_TAG
和ENTITY_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();
}