我正在尝试解析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();
但是我在myparser.getName()获得java.lang.NullPointerException;上面的日志也显示了" sdfdsf null"。
我做错了什么?
答案 0 :(得分: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;
编辑:
的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;
}
}
答案 1 :(得分:1)
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();
}