詳解Android之解析XML文件三種方式(DOM,PULL,SAX)
更新時間:2017年02月28日 08:43:43 作者:Android流光歲月
這篇文章主要介紹了詳解Android之解析XML文件三種方式,主要包括DOM,PULL,SAX,有興趣的可以了解一下。
1.xml文件代碼
<?xml version="1.0" encoding="UTF-8" ?> <%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ page isELIgnored="false" %> <fqs> <c:forEach items="${fqs}" var="fq"> <fq name="${fq.name}"> <content>${fq.content}</content> <time>${fq.time}</time> </fq> </c:forEach> </fqs>
2.XML網頁效果圖
3.Android代碼
1.布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="getXML" android:text="獲取XML數據" /> <ListView android:id="@+id/lv_main_list" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main_pull" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="getPULL" android:text="獲取PULL數據" /> <ListView android:id="@+id/lv_mainpull_list" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main_sax" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="getSAX" android:text="獲取SAX數據" /> <ListView android:id="@+id/lv_mainsax_list" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/tv_item_listview_name" android:layout_weight="1"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/tv_item_listview_content" android:layout_weight="1"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:id="@+id/tv_item_listview_time" android:layout_weight="1"/> </LinearLayout>
2.java代碼
DOM解析代碼
public class MainActivity extends AppCompatActivity { private ListView lv_main_list; private ProgressDialog progressDialog; private List<FQ> fqs = new ArrayList<>(); private MyAdapter myadapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv_main_list = (ListView) findViewById(R.id.lv_main_list); myadapter = new MyAdapter(); lv_main_list.setAdapter(myadapter); progressDialog = new ProgressDialog(this); progressDialog.setMessage("小青正在拼命加載中....."); } class MyAdapter extends BaseAdapter{ @Override public int getCount() { return fqs.size(); } @Override public Object getItem(int position) { return fqs.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null){ convertView=LayoutInflater.from(MainActivity.this).inflate(R.layout.item_list,null); ItemTag itemTag=new ItemTag(); itemTag.tv_name= (TextView) convertView.findViewById(R.id.tv_item_listview_name); itemTag.tv_content= (TextView) convertView.findViewById(R.id.tv_item_listview_content); itemTag.tv_tiem= (TextView) convertView.findViewById(R.id.tv_item_listview_time); convertView.setTag(itemTag); } ItemTag itemTag= (ItemTag) convertView.getTag(); itemTag.tv_name.setText(fqs.get(position).getName()); itemTag.tv_content.setText(fqs.get(position).getContent()); itemTag.tv_tiem.setText(fqs.get(position).getTime()); return convertView; } } public void getXML(View view) { new MyTask().execute(); } class MyTask extends AsyncTask { //獲取數據前 @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected Object doInBackground(Object[] params) { //獲取網絡數據 //1.定義獲取網絡的數據的路徑 String path = "http://192.168.43.149:8080/dataResult.xhtml"; //2.實例化URL try { URL url = new URL(path); //3.獲取鏈接對象 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //4.設置請求 httpURLConnection.setRequestMethod("GET"); //5.設置請求鏈接超時的時間 httpURLConnection.setConnectTimeout(5000); //6.獲取響應碼 int code = httpURLConnection.getResponseCode(); if (code == 200) { //7.獲取返回過來的數據(XML) InputStream is = httpURLConnection.getInputStream(); //8.使用DOM解析XML文件 DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); Document document=documentBuilder.parse(is); //獲取根標簽 Element root=document.getDocumentElement(); NodeList nodeList = root.getElementsByTagName("fq"); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); //獲取屬性name String name = element.getAttribute("name"); //獲取子標簽content,time Element elementContent = (Element) element.getElementsByTagName("content").item(0); String content = elementContent.getTextContent(); Element elementTime = (Element) element.getElementsByTagName("time").item(0); String time = elementTime.getTextContent(); FQ fq = new FQ(name, content, time); fqs.add(fq); } } } catch (Exception e) { e.printStackTrace(); } return fqs; } //獲取數據后更新UI @Override protected void onPostExecute(Object o) { super.onPostExecute(o); progressDialog.cancel(); myadapter.notifyDataSetChanged(); } } }
PULL解析代碼
public class MainPullActivity extends AppCompatActivity { private ListView lv_mainpull_list; private ProgressDialog progressDialog; private List<FQ> fqs = new ArrayList<>(); private MyAdapter myadapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_pull); myadapter = new MyAdapter(); lv_mainpull_list = (ListView) findViewById(R.id.lv_mainpull_list); lv_mainpull_list.setAdapter(myadapter); progressDialog = new ProgressDialog(this); progressDialog.setMessage("小青正在拼命加載中....."); } class MyAdapter extends BaseAdapter { @Override public int getCount() { return fqs.size(); } @Override public Object getItem(int position) { return fqs.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(MainPullActivity.this).inflate(R.layout.item_list, null); ItemTag itemTag = new ItemTag(); itemTag.tv_name = (TextView) convertView.findViewById(R.id.tv_item_listview_name); itemTag.tv_content = (TextView) convertView.findViewById(R.id.tv_item_listview_content); itemTag.tv_tiem = (TextView) convertView.findViewById(R.id.tv_item_listview_time); convertView.setTag(itemTag); } ItemTag itemTag = (ItemTag) convertView.getTag(); itemTag.tv_name.setText(fqs.get(position).getName()); itemTag.tv_content.setText(fqs.get(position).getContent()); itemTag.tv_tiem.setText(fqs.get(position).getTime()); return convertView; } } public void getPULL(View view) { new MyTask().execute(); } class MyTask extends AsyncTask { private FQ fq; //獲取數據前 @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected Object doInBackground(Object[] params) { //獲取網絡數據 //1.定義獲取網絡的數據的路徑 String path = "http://192.168.43.149:8080/dataResult.xhtml"; //2.實例化URL try { URL url = new URL(path); //3.獲取鏈接對象 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //4.設置請求 httpURLConnection.setRequestMethod("GET"); //5.設置請求鏈接超時的時間 httpURLConnection.setConnectTimeout(5000); //6.獲取響應碼 int code = httpURLConnection.getResponseCode(); if (code == 200) { //7.獲取返回過來的數據(XML) InputStream is = httpURLConnection.getInputStream(); //8.解析XML //使用PULL解析XML文件 XmlPullParser pullParser= Xml.newPullParser(); pullParser.setInput(is,"UTF-8"); int type=pullParser.getEventType(); while (type!=XmlPullParser.END_DOCUMENT){ switch (type){ case XmlPullParser.START_TAG: //獲取開始標簽名字 String startTafName=pullParser.getName(); if("fq".equals(startTafName)){ fq = new FQ(); String name=pullParser.getAttributeValue(0); fq.setName(name); }else if ("content".equals(startTafName)){ String content=pullParser.nextText(); fq.setContent(content); }else if ("time".equals(startTafName)){ String time=pullParser.nextText(); fq.setTime(time); } break; case XmlPullParser.END_TAG: //獲取接受標簽的名字 String endtagname=pullParser.getName(); if("fq".equals(endtagname)){ fqs.add(fq); } break; } type=pullParser.next(); } } } catch (Exception e) { e.printStackTrace(); } return fqs; } //獲取數據后更新UI @Override protected void onPostExecute(Object o) { super.onPostExecute(o); progressDialog.cancel(); myadapter.notifyDataSetChanged(); } } }
SAX解析代碼
public class MainSaxActivity extends AppCompatActivity { private ListView lv_mainsax_list; private ProgressDialog progressDialog; private List<FQ> fqs = new ArrayList<>(); private MyAdapter myadapter; private String currentTag = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_sax); lv_mainsax_list = (ListView) findViewById(R.id.lv_mainsax_list); myadapter = new MyAdapter(); lv_mainsax_list.setAdapter(myadapter); progressDialog = new ProgressDialog(this); progressDialog.setMessage("小青正在拼命加載中....."); } class MyAdapter extends BaseAdapter { @Override public int getCount() { return fqs.size(); } @Override public Object getItem(int position) { return fqs.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(MainSaxActivity.this).inflate(R.layout.item_list, null); ItemTag itemTag = new ItemTag(); itemTag.tv_name = (TextView) convertView.findViewById(R.id.tv_item_listview_name); itemTag.tv_content = (TextView) convertView.findViewById(R.id.tv_item_listview_content); itemTag.tv_tiem = (TextView) convertView.findViewById(R.id.tv_item_listview_time); convertView.setTag(itemTag); } ItemTag itemTag = (ItemTag) convertView.getTag(); itemTag.tv_name.setText(fqs.get(position).getName()); itemTag.tv_content.setText(fqs.get(position).getContent()); itemTag.tv_tiem.setText(fqs.get(position).getTime()); return convertView; } } public void getSAX(View view) { new MyTask().execute(); } class MyTask extends AsyncTask { private FQ fq; //獲取數據前 @Override protected void onPreExecute() { super.onPreExecute(); progressDialog.show(); } @Override protected Object doInBackground(Object[] params) { //獲取網絡數據 //1.定義獲取網絡的數據的路徑 String path = "http://192.168.43.149:8080/dataResult.xhtml"; //2.實例化URL try { URL url = new URL(path); //3.獲取鏈接對象 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //4.設置請求 httpURLConnection.setRequestMethod("GET"); //5.設置請求鏈接超時的時間 httpURLConnection.setConnectTimeout(5000); //6.獲取響應碼 int code = httpURLConnection.getResponseCode(); if (code == 200) { //7.獲取返回過來的數據(XML) InputStream is = httpURLConnection.getInputStream(); //8.解析XML //使用SAX解析XML文件 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); currentTag = localName; if ("fq".equals(localName)) { //實例化對象 fq = new FQ(); String name = attributes.getValue(0); fq.setName(name); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); currentTag=null; if ("fq".equals(localName)){ fqs.add(fq); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); if ("content".equals(currentTag)) { String content = new String(ch, start, length); fq.setContent(content); }else if ("time".equals(currentTag)) { String time = new String(ch, start, length); fq.setTime(time); } } }); } } catch (Exception e) { e.printStackTrace(); } return fqs; } //獲取數據后更新UI @Override protected void onPostExecute(Object o) { super.onPostExecute(o); progressDialog.cancel(); myadapter.notifyDataSetChanged(); } } }
實體類
public class FQ { private String name; private String content; private String time; public FQ(){} public FQ(String name, String time, String content) { this.name = name; this.time = time; this.content = content; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } } public class ItemTag { public TextView tv_name; public TextView tv_content; public TextView tv_tiem; }
配置文件添加聯網權限
<!-- 添加聯網的權限 --> <uses-permission android:name="android.permission.INTERNET" />
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android 在 res/layout 文件夾 下創(chuàng)建一個 子文件夾實例
這篇文章主要介紹了Android 在 res/layout 文件夾 下創(chuàng)建一個 子文件夾實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android開發(fā)之圖形圖像與動畫(四)AnimationListener簡介
就像Button控件有監(jiān)聽器一樣,動畫效果也有監(jiān)聽器,只需要實現AnimationListener就可以實現對動畫效果的監(jiān)聽,感興趣的朋友可以了解下啊,希望本文對你有所幫助2013-01-01Android 中從屏幕左下角彈出Dialog動畫效果的實現代碼
這篇文章主要介紹了Android 中從屏幕左下角彈出Dialog動畫效果的實現代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12Android webview 遇到android.os.FileUriExposedException錯誤解決辦法
這篇文章主要介紹了Android webview 遇到android.os.FileUriExposedException錯誤解決辦法的相關資料,希望通過本文能幫助到大家,讓大家遇到這樣的問題解決,需要的朋友可以參考下2017-10-10