1.android解析XML文件(采用Pull解析器解析文件)
测试方法:
/**
* 读取数据
* @param xml 文件
* @return 返回数据
* @throws Exception
*/
public static List<City> getCitys(InputStream xml) throws Exception {
List<City> citys = null;
City city = null;
// 得到解析器:第一种方式:XmlPullParserFactory.newInstance().newPullParser();
// 第二种方式:Xml.newPullParser();
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(xml, "UTF-8");
int event = pullParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_DOCUMENT:
citys = new ArrayList<City>();
break;
case XmlPullParser.START_TAG:
if ("china".equals(pullParser.getName())) {
int id = new Integer(pullParser.getAttributeValue(0));
city = new City();
city.setId(id);
}
if ("city".equals(pullParser.getName())) {
String cityname = pullParser.nextText();
city.setCity(cityname);
}
if ("province".equals(pullParser.getName())) {
String province = pullParser.nextText();
city.setProvince(province);
}
break;
case XmlPullParser.END_TAG:
if ("china".equals(pullParser.getName())) {
citys.add(city);
city = null;
}
break;
}
event = pullParser.next();
}
return citys;
}
/**
* 保存数据
* @param citys 需要保存的数据
* @param out 输出方向
* @throws Exception
*/
public static void save(List<City> citys,OutputStream out)throws Exception{
XmlSerializer serializer=Xml.newSerializer();//实例化器
serializer.setOutput(out,"UTF-8");
//设置xml文件的编码格式,第二个参数表示这个xml文件是否可以单独存在,而不是依赖其他文件
serializer.startDocument("UTF-8", true);
//第一个参数表示是否需要指定命名空间,第二个参数表示节点的名称
serializer.startTag(null, "citys");
for (City city : citys) {
serializer.startTag(null, "china");
//第一个参数表示是否需要指定命名空间,第二个参数表示节点的名称,第三个参数表示节点的值
serializer.attribute(null, "id", city.getId().toString());
serializer.startTag(null, "city");
serializer.text(city.getCity());
serializer.endTag(null, "city");
serializer.startTag(null, "province");
serializer.text(city.getProvince());
serializer.endTag(null, "province");
serializer.endTag(null, "china");
}
serializer.endTag(null, "citys");
serializer.endDocument();
out.flush();
out.close();
}
测试方法:
public void testCity()throws Exception{
InputStream xml=this.getClass().getClassLoader().getResourceAsStream("city.xml");
List<City> citys=CityService.getCitys(xml);
for (City city : citys) {
System.out.print(city.toString());
}
}
public void testSave()throws Exception{
List<City> citys=new ArrayList<City>();
citys.add(new City(1, "武汉", "湖北"));
citys.add(new City(2, "南昌", "江西"));
File xmFile=new File(getContext().getFilesDir(),"lht.text");
FileOutputStream outputStream=new FileOutputStream(xmFile);
CityService.save(citys, outputStream);
}