大家好,又见面了,我是你们的朋友全栈君。
Android解析XML文件》
XmlResourceParer是XmlPullParser的子类),其它位置情况都可以获取XML文档,返回一个Inputstream对象,进行读取数据,获取方法分别如下:
XmlResourceParser xmlParser = this.getResources().getXml(R.xml.XXX);
b.在res/xml、res/raw目录下:
InputStream inputStream = this.getResources().openRawResource(R.xml.XXX);
InputStream inputStream = getResources().getAssets().open(fileName);
d.在应用指定目录下(SDcard,应用data目录等):
// path路径根据实际项目修改,此次获取SDcard根目录String path = Environment.getExternalStorageDirectory().toString();File xmlFlie = new File(path+fileName);InputStream inputStream = new FileInputStream(xmlFlie);
/** * 读取url的xml资源 转成String * @param url * @return 返回 读取url的xml字符串 */ public String getStringByUrl(String url) { String outputString = ""; // DefaultHttpClient DefaultHttpClient httpclient = new DefaultHttpClient(); // HttpGet HttpGet httpget = new HttpGet(url); // ResponseHandler ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { outputString = httpclient.execute(httpget, responseHandler); outputString = new String(outputString.getBytes("ISO-8859-1"), "utf-8"); // 解决中文乱码 Log.i("HttpClientConnector", "连接成功"); } catch (Exception e) { Log.i("HttpClientConnector", "连接失败"); e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); return outputString; }
1、事件回调类型
START_DOCUMENT(0)
END_DOCUMENT (1)
START_TAG (2)
END_TAG (3)
TEXT (4)
getEventType() : Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.) 【获取当前事件回调类型】
getName():For START_TAG or END_TAG events, the (local) name of the current element is returned when namespaces are enabled.【获取当前节点名字】
getAttributeValue(int index):Returns the given attributes value.【根据id获取节点属性值】
getAttributeValue(String namespace, String name):Returns the attributes value identified by namespace URI and namespace localName.【根据name获取节点属性值】
netxText():If current event is START_TAG then if next element is TEXT then element content is returned or if next event is END_TAG then empty string is returned, otherwise exception is thrown.【回调节点START_TAG时,通过此方法获取节点内容】
try { //开始解析事件 int eventType = parser.getEventType(); //处理事件,不碰到文档结束就一直处理 while (eventType != XmlPullParser.END_DOCUMENT) { //因为定义了一堆静态常量,所以这里可以用switch switch (eventType) { case XmlPullParser.START_DOCUMENT: // 不做任何操作或初开始化数据 break; case XmlPullParser.START_TAG: // 解析XML节点数据 // 获取当前标签名字 String tagName = parser.getName(); if(tagName.equals("XXXTAGXXX")){ // 通过getAttributeValue 和 netxText解析节点的属性值和节点值 } break; case XmlPullParser.END_TAG: // 单节点完成,可往集合里边添加新的数据 break; case XmlPullParser.END_DOCUMENT: break; } // 别忘了用next方法处理下一个事件,不然就会死循环 eventType = parser.next(); }} catch (XmlPullParserException e) { e.printStackTrace();}catch (IOException e) { e.printStackTrace();}
主要代码:
/** * 同样删除首行,才能解析成功, * @param fileName * @return 返回xml文件的inputStream */ public InputStream getInputStreamFromAssets(String fileName){ try { InputStream inputStream = getResources().getAssets().open(fileName); return inputStream; } catch (IOException e) { e.printStackTrace(); } return null; } /** * 读取XML文件,xml文件放到res/xml文件夹中,若XML为本地文件,则推荐该方法 * * @param fileName * @return : 读取到res/xml文件夹下的xml文件,返回XmlResourceParser对象(XmlPullParser的子类) */ public XmlResourceParser getXMLFromResXml(String fileName){ XmlResourceParser xmlParser = null; try { //*/ // xmlParser = this.getResources().getAssets().openXmlResourceParser("assets/"+fileName); // 失败,找不到文件 xmlParser = this.getResources().getXml(R.xml.provinceandcity); /*/ // xml文件在res目录下 也可以用此方法返回inputStream InputStream inputStream = this.getResources().openRawResource(R.xml.provinceandcity); /*/ return xmlParser; } catch (Exception e) { e.printStackTrace(); } return xmlParser; } /** * 读取url的xml资源 转成String * @param url * @return 返回 读取url的xml字符串 */ public String getStringByUrl(String url) { String outputString = ""; // DefaultHttpClient DefaultHttpClient httpclient = new DefaultHttpClient(); // HttpGet HttpGet httpget = new HttpGet(url); // ResponseHandler ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { outputString = httpclient.execute(httpget, responseHandler); outputString = new String(outputString.getBytes("ISO-8859-1"), "utf-8"); // 解决中文乱码 Log.i("HttpClientConnector", "连接成功"); } catch (Exception e) { Log.i("HttpClientConnector", "连接失败"); e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); return outputString; } /** * 解析SDcard xml文件 * @param fileName * @return 返回xml文件的inputStream */ public InputStream getInputStreamFromSDcard(String fileName){ try { // 路径根据实际项目修改 String path = Environment.getExternalStorageDirectory().toString() + "/test_xml/"; Log.v("", "path : " + path); File xmlFlie = new File(path+fileName); InputStream inputStream = new FileInputStream(xmlFlie); return inputStream; } catch (IOException e) { e.printStackTrace(); } return null; }
b.多线程解析:
/**
* 多线程加载网络端的xml,若xml文件过大也需要用该方式加载
*/
Handler mHandler = new Handler();
Runnable mRunnable = new Runnable() {
public void run() {
if(!isFinishParser){
mHandler.postDelayed(mRunnable, 1000);
}else{
showView.setText(provinceStr);
mHandler.removeCallbacks(mRunnable);
}
}
};
/**
* 比较耗时操作新建一个线程,避免UI线程ANR
*/
public void parserWhitThread(){
new Thread(){
@Override
public void run() {
provinceandcityStr = getStringByUrl(provinceAndCityUrl);
provinceArray = ProvincePullParse.Parse(provinceandcityStr);
for(Province pro : provinceArray){
provinceStr += pro.getProvinceId() + " : " +pro.getProvinceName()+"\n";
}
isFinishParser = true;
}
}.start();
}
public static ArrayList<City> ParseXml(XmlPullParser parser){
ArrayList<City> CityArray = new ArrayList<City>();
City CityTemp = null;
int provinceId = 0;
int cityId;
String cityName;
try {
//开始解析事件
int eventType = parser.getEventType();
//处理事件,不碰到文档结束就一直处理
while (eventType != XmlPullParser.END_DOCUMENT) {
//因为定义了一堆静态常量,所以这里可以用switch
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
//给当前标签起个名字
String tagName = parser.getName();
// Log.d("", "====XmlPullParser.START_TAG=== tagName: " + tagName);
if(tagName.equals("province")){
provinceId = Integer.parseInt(parser.getAttributeValue(0));
}else if(tagName.equals("item")){
CityTemp = new City();
}else if(tagName.equals("id")){
cityId = Integer.parseInt(parser.nextText());
parser.next();
cityName = parser.nextText();
Log.v("", "id getText: "+cityId);
Log.v("", "name getText: "+cityName);
Log.e("", "=========================");
CityTemp.setProvinceId(provinceId);
CityTemp.setCityId(cityId);
CityTemp.setCityName(cityName);
CityArray.add(CityTemp);
}
break;
case XmlPullParser.END_TAG:
break;
case XmlPullParser.END_DOCUMENT:
break;
}
//别忘了用next方法处理下一个事件,忘了的结果就成死循环#_#
eventType = parser.next();
}
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return CityArray;
}
http://android.yaohuiji.com/archives/935
http://www.cnblogs.com/zhangdongzi/archive/2011/04/14/2016434.html
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/158838.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...