学习参考资源:https://www.gitbook.com/book/zhangqx/mini-weather/details
前面我们设置好了基本的屏幕布局、通过url获取到了网络中的天气预报数据,接下来我们要将这个XML格式的天气数据解析开来。
通过xmlPullParser解析xml数据
1.待解析的xml格式数据
2.根据标签值,获取标签数据
因为我们这个网页中fengli、fengxiang等标签出现了不止一次,因此我们设置了计数器以便只打印第一次
parseXML(String)函数如下:
private void parseXML(String xmlData)
{
int fengliCount = 0;
int fengxiangCount = 0;
int dateCount = 0;
int highCount = 0;
int lowCount = 0;
int typeCount = 0;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
int eventType = xmlPullParser.getEventType();
Log.d("MWeater","start parse xml");
while(eventType!=xmlPullParser.END_DOCUMENT)
{
switch (eventType)
{
//文档开始位置
case XmlPullParser.START_DOCUMENT:
Log.d("parse","start doc");
break;
//标签元素开始位置
case XmlPullParser.START_TAG:
if(xmlPullParser.getName().equals("city"))
{
eventType=xmlPullParser.next();
Log.d("city",xmlPullParser.getText());
}else if(xmlPullParser.getName().equals("updatetime"))
{
eventType=xmlPullParser.next();
Log.d("updatetime",xmlPullParser.getText());
}else if(xmlPullParser.getName().equals("wendu"))
{
eventType=xmlPullParser.next();
Log.d("wendu",xmlPullParser.getText());
}else if(xmlPullParser.getName().equals("fengli") && fengliCount==0 )
{
eventType=xmlPullParser.next();
Log.d("fengli",xmlPullParser.getText());
fengliCount++;
}else if(xmlPullParser.getName().equals("shidu"))
{
eventType=xmlPullParser.next();
Log.d("shidu",xmlPullParser.getText());
}else if(xmlPullParser.getName().equals("fengxiang") && fengxiangCount== 0)
{
eventType=xmlPullParser.next();
Log.d("fengxiang",xmlPullParser.getText());
fengxiangCount++;
}else if(xmlPullParser.getName().equals("pm25"))
{
eventType=xmlPullParser.next();
Log.d("pm25",xmlPullParser.getText());
}else if(xmlPullParser.getName().equals("quality"))
{
eventType=xmlPullParser.next();
Log.d("quelity",xmlPullParser.getText());
}else if(xmlPullParser.getName().equals("date") && dateCount==0 )
{
eventType=xmlPullParser.next();
Log.d("date",xmlPullParser.getText());
dateCount++;
}else if(xmlPullParser.getName().equals("high") && highCount==0 )
{
eventType=xmlPullParser.next();
Log.d("high",xmlPullParser.getText());
highCount++;
}else if(xmlPullParser.getName().equals("low") && lowCount==0 )
{
eventType=xmlPullParser.next();
Log.d("low",xmlPullParser.getText());
lowCount++;
}else if(xmlPullParser.getName().equals("type") && typeCount==0 )
{
eventType=xmlPullParser.next();
Log.d("type",xmlPullParser.getText());
typeCount++;
}
break;
case XmlPullParser.END_TAG:
break;
}
eventType=xmlPullParser.next();
}
}catch (Exception e)
{
e.printStackTrace();
}
}
3.在获取网页数据之后,调用这个函数
运行一下!