亲宝软件园·资讯

展开

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

Android流光岁月 人气:0
想了解详解Android之解析XML文件三种方式(DOM,PULL,SAX)的相关内容吗,Android流光岁月在本文为您仔细讲解android xml解析的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:android,xml解析,android,xml解析方式,android中xml解析方式,下面大家一起来学习吧。

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

加载全部内容

相关教程
猜你喜欢
用户评论