Android的XML文件解析之PULL解析
我是一个在校大学生,对安卓的学习完全是出于兴趣,因此,只能靠自己自学,有写的不好的地方希望大家多多包涵。
首先说明本人写博客的目的,完全是为了对自己Android学习的总结,如果文章对你的学习和工作有所帮助,本人不胜荣幸。
当然,要解析XML文件,首先要有一个XML文件,下面我们自己新建一个XML文件,就以example.xml来命名一个文件。文件内容如下:
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?> <persons> <person id="001"> <name>fnhfire7030</name> <age>21</age> </person> <person id="002"> <name>fnhfire7030</name> <age>23</age> </person> </persons>
然后我们就要建立一个解析器来解析XML文件,这里我们命名为PullXMLTools.java,具体内容如以下代码:
<pre name="code" class="java">package com.study.xiaohui.myapplication.parse; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Created by xiaohui on 2016/3/2. * 建立一个解析XML文件的类 */ public class PullXMLTools { public List<PullXMLInfo> parseXML(InputStream inputStream, String encode) throws XmlPullParserException, IOException { List<PullXMLInfo> list = null; PullXMLInfo pullXMLInfo = null; //建立解析工厂 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); //获得XML文件的引用 XmlPullParser pullParser = factory.newPullParser(); //从服务器下载XML文件,以流的形式返回,设定解析XML文件的编码格式 pullParser.setInput(inputStream, encode); int eventType = pullParser.getEventType(); //对XML文件进行解析 while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<PullXMLInfo>(); break; case XmlPullParser.START_TAG: if ("person".equals(pullParser.getName())) { pullXMLInfo = new PullXMLInfo(); int id = Integer.parseInt(pullParser.getAttributeValue(0)); pullXMLInfo.setId(id); } else if ("name".equals(pullParser.getName())) { String name = pullParser.nextText(); pullXMLInfo.setName(name); } else if ("age".equals(pullParser.getName())) { int age = Integer.parseInt(pullParser.nextText()); pullXMLInfo.setAge(age); } break; case XmlPullParser.END_TAG: if ("person".equals(pullParser.getName())) { list.add(pullXMLInfo); pullXMLInfo = null; } break; } eventType = pullParser.next(); } return list; } }
当然解析时,我们要定义一个实体类方便解析,我把实体类命名为PullXMLInfo.java,内容如下:
<span style="font-size:18px;">package com.study.xiaohui.myapplication.parse; /** * Created by xiaohui on 2016/3/2. */ public class PullXMLInfo { public int id = 0; public String name = null; public int age = 0; public PullXMLInfo(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public PullXMLInfo() { } @Override public String toString() { return "PullXMLInfo{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } </span>
因为我的XML文件是在我的tomcat中,因此需要写一个下载XML文件的方法,这里我自己重新定义了一个Downloader的类,里面的内容如下:
package com.study.xiaohui.myapplication.downloader; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by xiaohui on 2016/3/2. * 从本机下载XML文件 */ public class DownLoader { private URL url = null; public InputStream downloader(String str) { InputStream inputStream = null; try { url = new URL(str); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //设置连接超时的时间 connection.setConnectTimeout(3000); connection.setDoInput(true); connection.setRequestMethod("GET"); //获取网络返回的状态码 int responseCode = connection.getResponseCode(); if (responseCode == 200) { inputStream = connection.getInputStream(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return inputStream; } }
上面就是下载和解析XML文件的所有代码,我已经全部贴出,最后就是在Activity中调用了,好像从Android4.0开始就不能直接在主线程中下载文了,因此我继承了AsyncTask这个类。在这里就把代码全部贴出了吧!
package com.study.xiaohui.myapplication; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.study.xiaohui.myapplication.downloader.DownLoader; import com.study.xiaohui.myapplication.parse.PullXMLInfo; import com.study.xiaohui.myapplication.parse.PullXMLTools; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.List; public class MainActivity extends AppCompatActivity { //本机XML文件的位置 private String PATH = "http://192.168.1.101:82/mp3/example.xml"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //调用LongTasks LongTasks longTasks = new LongTasks(); longTasks.execute(); } //主线程中不能直接同网络下载内容,因此重新定义了一个继承AsyncTask的类 class LongTasks extends AsyncTask<String, Void, List> { String str = PATH; @Override protected List doInBackground(String... params) { //定义一个List List<PullXMLInfo> list = null; DownLoader downLoader = new DownLoader(); PullXMLTools pullXMLTools = new PullXMLTools(); InputStream inputStream = downLoader.downloader(str); try { list = pullXMLTools.parseXML(inputStream, "utf-8"); //读取List中的内容通过Log显示出来 for (PullXMLInfo pullXMLInfo : list) { Log.i("fnhFire", "" + pullXMLInfo.toString()); } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(List list) { super.onPostExecute(list); } } }
到这里使用Pull解析XML文件的步骤就全部完成了。上面的代码全部是本人亲测通过的,希望能对大家的学习和工作有所帮助。下面是解析出来的内容,我们与XML文件的内容对照发现完全一致。