主程序:
List<WeatherInfo> smsinfos = getSmsinfos(MainActivity.class
.getClassLoader().getResourceAsStream("weathers.xml"));
// 注意weather.xml在src目录下
StringBuilder sbBuilder = new StringBuilder();
for (WeatherInfo smsinfo : smsinfos) {
String strinfo = smsinfo.toString();
sbBuilder.append(strinfo);
sbBuilder.append("\n");
}
tView.setText(sbBuilder.toString());
解析代码:
public List<WeatherInfo> getSmsinfos(InputStream is)
throws XmlPullParserException, IOException {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");
List<WeatherInfo> weList = null;
WeatherInfo smsinfo = null;
int type = parser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:// 注意是tag
if ("infos".equals(parser.getName())) {
weList = new ArrayList<WeatherInfo>();
} else if ("city".equals(parser.getName())) {
smsinfo = new WeatherInfo();
String idString = parser.getAttributeValue(0);
// 是value 不是name
smsinfo.setId(idString);
} else if ("name".equals(parser.getName())) {
String name = parser.nextText();
smsinfo.setName(name);
} else if ("wind".equals(parser.getName())) {
String wind = parser.nextText();
smsinfo.setWind(wind);
}
break;
case XmlPullParser.END_TAG:
if ("city".equals(parser.getName())) {
weList.add(smsinfo);
smsinfo = null;// 制空叫jvm回收
}
break;
}
type = parser.next();
// 注意这句话别忘写了
}
return weList;
}
bean类
private String id;
private String name;
private String wind;
可用Eclipse快捷键生成
1:生成get set方法 代码处右键-->Source-->Generate Getters and Setters
2: 生成构造方法 代码处右键-->Source-->Generate Constructtor using Fields
3: 生成tostring 代码处右键-->Source-->Generate tostirng
资源xml,存放位置在src目录下
内容
<?xml version="1.0" encoding="utf-8" ?>
<infos>
<city id="1">
<name>北京</name>
<wind>南风</wind>
</city>
<city id="2">
<name>天津</name>
<wind>北风</wind>
</city>
<city id="3">
<name>邯郸</name>
<wind>西风</wind>
</city>
</infos>