欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-13 20:41:22
1.xml文件代码 <%@ page la...

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网页效果图

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

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" />

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: