pull解析省市xml数据

前端之家收集整理的这篇文章主要介绍了pull解析省市xml数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

public static ArrayList<CityData> readCityXML(InputStream inStream) {
ArrayList<CityData> provinceDataList = null;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(inStream,"UTF-8");
int eventType = parser.getEventType();
CityData provinceData = null;
ArrayList<CityData.City> cityArrayList=null;
CityData.City city = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT://文档开始事件,可以进行数据初始化处理
provinceDataList = new ArrayList<CityData>();
break;
case XmlPullParser.START_TAG://开始元素事件
String name = parser.getName();
if ("province".equals(name)) {
provinceData=new CityData();
// cityList=new ArrayList<ArrayList<CityData.City>>();
cityArrayList=new ArrayList<>();
String cityName = parser.getAttributeValue(0);
String provinceCode = parser.getAttributeValue(1);
provinceData.setProvinceName(cityName);
provinceData.setProvinceCode(provinceCode);
}
if ("city".equals(name)) {
city = new CityData.City();
String cityName = parser.getAttributeValue(0);
String cityCode = parser.getAttributeValue(1);
city.setCityName(cityName);
city.setCityCode(cityCode);
}
break;
case XmlPullParser.END_TAG://结束元素事件
if(("city").equals(parser.getName()) ){
cityArrayList.add(city);
provinceData.setCityList(cityArrayList);
city=null;
}
if (("province").equals(parser.getName()) && provinceData != null) {
provinceDataList.add(provinceData);
provinceData = null;
}
break;

}
eventType = parser.next();
}
inStream.close();
return provinceDataList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//调用

InputStream inputStream = null;
try {
inputStream = getAssets().open("ProvinceData.xml");
provinceDataList= PullCityDataForXml.readCityXML(inputStream);

initPickerView(provinceStr,cityList);
} catch (IOException e) {
e.printStackTrace();
}

省市XML文件

<province name="北京市" provinceCode="1"> <city name="北京市" cityCode="1001"/> </province> <province name="天津市" provinceCode="2"> <city name="天津市" cityCode="1002"/> </province> <province name="河北省" provinceCode="3"> <city name="石家庄市" cityCode="1003"/> <city name="唐山市" cityCode="1004"/> <city name="秦皇岛市" cityCode="1005"/> <city name="邯郸市" cityCode="1006"/> <city name="邢台市" cityCode="1007"/> <city name="保定市" cityCode="1008"/> <city name="张家口市" cityCode="1009"/> <city name="承德市" cityCode="1010"/> <city name="沧州市" cityCode="1011"/> <city name="廊坊市" cityCode="1012"/> <city name="衡水市" cityCode="1013"/> </province>

猜你在找的XML相关文章