国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

詳解Android之解析XML文件三種方式(DOM,PULL,SAX)

2019-10-23 19:44:33
字體:
供稿:網(wǎng)友

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網(wǎng)頁(yè)效果圖

android,xml解析,xml解析方式,android中xml解析方式

3.Android代碼

1.布局文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android/196097.html">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數(shù)據(jù)" />  <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數(shù)據(jù)" />  <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數(shù)據(jù)" />  <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 {    //獲取數(shù)據(jù)前    @Override    protected void onPreExecute() {      super.onPreExecute();      progressDialog.show();    }    @Override    protected Object doInBackground(Object[] params) {      //獲取網(wǎng)絡(luò)數(shù)據(jù)      //1.定義獲取網(wǎng)絡(luò)的數(shù)據(jù)的路徑      String path = "http://192.168.43.149:8080/dataResult.xhtml";      //2.實(shí)例化URL      try {        URL url = new URL(path);        //3.獲取鏈接對(duì)象        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();        //4.設(shè)置請(qǐng)求        httpURLConnection.setRequestMethod("GET");        //5.設(shè)置請(qǐng)求鏈接超時(shí)的時(shí)間        httpURLConnection.setConnectTimeout(5000);        //6.獲取響應(yīng)碼        int code = httpURLConnection.getResponseCode();        if (code == 200) {          //7.獲取返回過來的數(shù)據(jù)(XML)          InputStream is = httpURLConnection.getInputStream();          //8.使用DOM解析XML文件          DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();          DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();          Document document=documentBuilder.parse(is);          //獲取根標(biāo)簽          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");            //獲取子標(biāo)簽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;    }    //獲取數(shù)據(jù)后更新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;    //獲取數(shù)據(jù)前    @Override    protected void onPreExecute() {      super.onPreExecute();      progressDialog.show();    }    @Override    protected Object doInBackground(Object[] params) {      //獲取網(wǎng)絡(luò)數(shù)據(jù)      //1.定義獲取網(wǎng)絡(luò)的數(shù)據(jù)的路徑      String path = "http://192.168.43.149:8080/dataResult.xhtml";      //2.實(shí)例化URL      try {        URL url = new URL(path);        //3.獲取鏈接對(duì)象        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();        //4.設(shè)置請(qǐng)求        httpURLConnection.setRequestMethod("GET");        //5.設(shè)置請(qǐng)求鏈接超時(shí)的時(shí)間        httpURLConnection.setConnectTimeout(5000);        //6.獲取響應(yīng)碼        int code = httpURLConnection.getResponseCode();        if (code == 200) {          //7.獲取返回過來的數(shù)據(jù)(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:                //獲取開始標(biāo)簽名字                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:                //獲取接受標(biāo)簽的名字                String endtagname=pullParser.getName();                if("fq".equals(endtagname)){                  fqs.add(fq);                }                break;            }            type=pullParser.next();          }        }      } catch (Exception e) {        e.printStackTrace();      }      return fqs;    }    //獲取數(shù)據(jù)后更新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;    //獲取數(shù)據(jù)前    @Override    protected void onPreExecute() {      super.onPreExecute();      progressDialog.show();    }    @Override    protected Object doInBackground(Object[] params) {      //獲取網(wǎng)絡(luò)數(shù)據(jù)      //1.定義獲取網(wǎng)絡(luò)的數(shù)據(jù)的路徑      String path = "http://192.168.43.149:8080/dataResult.xhtml";      //2.實(shí)例化URL      try {        URL url = new URL(path);        //3.獲取鏈接對(duì)象        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();        //4.設(shè)置請(qǐng)求        httpURLConnection.setRequestMethod("GET");        //5.設(shè)置請(qǐng)求鏈接超時(shí)的時(shí)間        httpURLConnection.setConnectTimeout(5000);        //6.獲取響應(yīng)碼        int code = httpURLConnection.getResponseCode();        if (code == 200) {          //7.獲取返回過來的數(shù)據(jù)(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)) {                //實(shí)例化對(duì)象                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;    }    //獲取數(shù)據(jù)后更新UI    @Override    protected void onPostExecute(Object o) {      super.onPostExecute(o);      progressDialog.cancel();      myadapter.notifyDataSetChanged();    }  }}

實(shí)體類

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;}

配置文件添加聯(lián)網(wǎng)權(quán)限

<!-- 添加聯(lián)網(wǎng)的權(quán)限 --><uses-permission android:name="android.permission.INTERNET" />

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到Android開發(fā)頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 顺义区| 永德县| 赤水市| 湘阴县| 邵武市| 仪征市| 南涧| 阿巴嘎旗| 蕲春县| 丹寨县| 叶城县| 裕民县| 洛扎县| 宜春市| 胶州市| 手游| 青铜峡市| 福海县| 定陶县| 博野县| 广南县| 体育| 崇义县| 凯里市| 农安县| 西林县| 抚远县| 新丰县| 轮台县| 海安县| 西峡县| 祁连县| 科尔| 合水县| 太保市| 宜川县| 林甸县| 平南县| 疏勒县| 潞城市| 琼结县|