一:xml解析
在Android中提供了三种解析XML的方式:SAX(Simple API XML),DOM(Document Objrect Model),以及Android推荐的Pull解析方式.
设定解析目标对象xml
<?xml version="1.0" encoding="utf-8"?>
<persons>
<person id="111">
<name>小路</name>
<age>11</age>
<image>a.jpg</image>
</person>
<person id="112">
<name>小鹿</name>
<age>12</age>
<image>b.jpg</image>
</person>
<person id="113">
<name>小陆</name>
<age>13</age>
<image>c.jpg</image>
</person>
<person id="114">
<name>小卢</name>
<age>14</age>
<image>d.jpg</image>
</person>
</persons>
1、DOM(,即对象文档模型,它是将整个XML文档一次性载入内存(效率较低,不推荐使用),每一个节点当做一个对象)
2、SAX(边读边解析,基于事件(方法)驱动方式)
3、使用PULL解析(类似SAX,android推荐)
解析流程(01.获取网络XML数据 02.解析XML 03.展示)
具体实现代码如下:
public void parseXML(View view) {
new MyTask().execute();
}
//线程间通信机制
//子线程+Handler
//异步任务类 AsyncTask
class MyTask extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
//(一).获取网络XML数据
//原生态底层:
//URLConnection
try {
URL url = new URL(getString(R.string.server_name)+"parseXML.xml");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod("GET");
//设置请求连接超时的时间(优化)
connection.setConnectTimeout(5000);
//获取结果码
int code = connection.getResponseCode();
if(code==200){
//获取服务器返回过来的结果
InputStream is = connection.getInputStream();
//(二)解析XML
//01.使用DOM解析
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//
// DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// Document document = documentBuilder.parse(is);
// //获取跟标签
// Element root = document.getDocumentElement();
// //获取<persons>下面的所有的子标签<person>
// NodeList nodeList = root.getElementsByTagName("person");
// for (int i = 0; i <nodeList.getLength() ; i++) {
// //获取单个
// //Node
// //Element
// Element personElement= (Element) nodeList.item(i);
// //获取<person>属性id的值
// String id=personElement.getAttribute("id");
// Log.i("test",id);
//
// //获取<person>下面的子标签<name><age><image>的值
// Element nameElement= (Element) personElement.getElementsByTagName("name").item(0);
// String name=nameElement.getTextContent();
// Element ageElement= (Element) personElement.getElementsByTagName("age").item(0);
// String age=ageElement.getTextContent();
// Element imageElement= (Element) personElement.getElementsByTagName("image").item(0);
// String image=imageElement.getTextContent();
//
// Log.i("test",name+" "+age+" "+image);
// }
//02.SAX(边读边解析,基于事件(方法)驱动方式)
// SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// SAXParser saxParser = saxParserFactory.newSAXParser();
// saxParser.parse(is,new DefaultHandler(){
// @Override
// public void startDocument() throws SAXException {
// super.startDocument();
// }
//
// @Override
// public void endDocument() throws SAXException {
// super.endDocument();
// }
//
// @Override
// public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// super.startElement(uri, localName, qName, attributes);
// cuurentTag=localName;
//获取开始标签的名字
// if("person".equals(localName)){
// //取属性的值
// String id=attributes.getValue(0);
// Log.i("test",id);
// }
// }
//
// @Override
// public void endElement(String uri, String localName, String qName) throws SAXException {
// super.endElement(uri, localName, qName);
// cuurentTag=null;
// }
//
// @Override
// public void characters(char[] ch, int start, int length) throws SAXException {
// super.characters(ch, start, length);
// if("name".equals(cuurentTag)){
// //获取<name>的值
// String name=new String(ch,start,length);
// Log.i("test", " "+name);
// }else if("age".equals(cuurentTag)){
// //获取<name>的值
// String age=new String(ch,start,length);
// Log.i("test", " "+age);
// }else if("image".equals(cuurentTag)){
// //获取<name>的值
// String image=new String(ch,start,length);
// Log.i("test", " "+image);
// }
// }
// });
//03.使用PULL解析(类似SAX)
XmlPullParser xmlPullParser = Xml.newPullParser();
xmlPullParser.setInput(is,"utf-8");
//获取解析的标签的类型
int type=xmlPullParser.getEventType();
while (type!=xmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_TAG:
//获取开始标签名字
String starttagName=xmlPullParser.getName();
if("person".equals(starttagName)){
//获取id的值
String id=xmlPullParser.getAttributeValue(0);
Log.i("test",id);
}else if("name".equals(starttagName)){
String name=xmlPullParser.nextText();
Log.i("test",name);
}else if("age".equals(starttagName)){
String age=xmlPullParser.nextText();
Log.i("test",age);
}else if("image".equals(starttagName)){
String image=xmlPullParser.nextText();
Log.i("test",image);
}
break;
case XmlPullParser.END_TAG:
break;
}
//细节:
type=xmlPullParser.next();
}
}
//结果码(状态)
//成功:200
//
//未修改:304
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (XmlPullParserException e) {
e.printStackTrace();
}
// catch (ParserConfigurationException e) {
// e.printStackTrace();
// } catch (SAXException e) {
// e.printStackTrace();
// }
// catch (ParserConfigurationException e) {
// e.printStackTrace();
// }catch (SAXException e) {
// e.printStackTrace();
// }
//(三).展示
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
二:Json解析
下面介绍三种(1.原生态 ( [] JsonArray {} JsonObject)、2.Gson(google)、3.FastJson(阿里巴巴))
设定解析目标Json
{
"list":2,
"persons":[{"pid":1,"pname":"张三","page":10},{"pid":1,"pname":"张三","page":10}]
}
具体代码实现
public void parseJson(View view) {
new MyTask().execute();
}
class MyTask extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
//一.获取网络Json数据
//原生态底层:
//URLConnection
try {
URL url = new URL(getString(R.string.server_name) + "persons.json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
int code = connection.getResponseCode();
if (code == 200) {
InputStream is = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String str = null;
StringBuffer stringBuffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
stringBuffer.append(str);
}
Log.i("test", "parseJson" + stringBuffer.toString());
//二.开始解析Json
//01.使用原生态
// JSONObject jsonObject=new JSONObject(stringBuffer.toString());
// int list=jsonObject.getInt("list");
// Log.i("test","长度:"+list);
//
// JSONArray jsonArray=jsonObject.getJSONArray("persons");
//
// for (int i = 0; i <jsonArray.length() ; i++) {
// JSONObject object=jsonArray.getJSONObject(i);
// int pid=object.getInt("pid");
// String pname=object.getString("pname");
// int page=object.getInt("page");
// Log.i("test",pid+" "+pname+" "+page);
// }
//02.使用Gson解析json
// Gson gson = new Gson();
// Bigperson bigperson = gson.fromJson(stringBuffer.toString(), Bigperson.class);
// Log.i("test", bigperson.getList() + "");
//
// List<SmallPerson> persons = bigperson.getPersons();
// for (SmallPerson person : persons) {
// Log.i("test", person.toString());
// }
//03.使用FastJson解析json
Bigperson bigperson = JSON.parseObject(stringBuffer.toString(),Bigperson.class);
List<SmallPerson> persons = bigperson.getPersons();
for (SmallPerson person : persons) {
Log.i("test", person.toString());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// catch (JSONException e) {
// e.printStackTrace();
// }
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}
三:注意
<uses-permission android:name="android.permission.INTERNET" />