android 中解析XML的方法

在XML解析和使用原始XML资源中都涉及过对XML的解析,之前使用的是 DOM4J和 XmlResourceParser 来解析的。本文中将使用XmlPullParser来解析,分别解析不同复杂度的test1.xml、test2.xml、test3.xml。代码如下:

MainActivity:

package com.home.xmlparsetest;



import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;



import org.xmlpull.v1.XmlPullParser;



import android.app.Activity;

import android.os.Bundle;

import android.util.Xml;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.ExpandableListView;



public class MainActivity extends Activity implements OnClickListener {

  private Button parseBtn1;

  private Button parseBtn2;

  private Button parseBtn3;

  private ExpandableListView listView;



  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    initWidget();

  }



  private void initWidget() {

    parseBtn1 = (Button) findViewById(R.id.main_btn_test1);

    parseBtn1.setOnClickListener(this);

    parseBtn2 = (Button) findViewById(R.id.main_btn_test2);

    parseBtn2.setOnClickListener(this);

    parseBtn3 = (Button) findViewById(R.id.main_btn_test3);

    parseBtn3.setOnClickListener(this);

    listView = (ExpandableListView) findViewById(R.id.list);

  }



  @Override

  public void onClick(View v) {

    if (v == parseBtn1) {

      InputStream is = getAssetsStream("test1.xml");

      List<ClassBean> list = parseFile1(is);

      listView.setAdapter(new MyAdapter(this, list));

    } else if (v == parseBtn2) {

      InputStream is = getAssetsStream("test2.xml");

      List<ClassBean> list = parseFile2(is);

      listView.setAdapter(new MyAdapter(this, list));

    } else if (v == parseBtn3) {

      InputStream is = getAssetsStream("test3.xml");

      List<ClassBean> list = parseFile3(is);

      listView.setAdapter(new MyAdapter(this, list));

    }

  }



  /**

   * 得到Assets里面相应的文件流

   * 

   * @param fileName

   * @return

   */

  private InputStream getAssetsStream(String fileName) {

    InputStream is = null;

    try {

      is = getAssets().open(fileName);

    } catch (IOException e) {

      e.printStackTrace();

    }

    return is;

  }



  /**

   * 解析test1.xml

   * 

   * @param is

   * @return list

   */

  private List<ClassBean> parseFile1(InputStream is) {

    List<ClassBean> list = new ArrayList<ClassBean>();

    try {

      XmlPullParser parser = Xml.newPullParser();

      parser.setInput(is, "utf-8");

      int event = parser.getEventType();

      while (event != XmlPullParser.END_DOCUMENT) {

        switch (event) {

        case XmlPullParser.START_DOCUMENT:

          break;

        case XmlPullParser.START_TAG:

          if ("class".equals(parser.getName())) {

            ClassBean bean = new ClassBean();

            bean.setId(parser.getAttributeValue(0));

            bean.setName(parser.nextText());

            list.add(bean);

          }

          break;

        }

        event = parser.next();

      }

    } catch (Exception e) {

      e.printStackTrace();

    }

    return list;

  }



  /**

   * 解析test2.xml

   * 

   * @param is

   * @return list

   */

  private List<ClassBean> parseFile2(InputStream is) {

    List<ClassBean> list = null;

    ClassBean bean = null;

    List<StudentBean> sList = null;

    StudentBean be = null;

    try {

      XmlPullParser parser = Xml.newPullParser();

      parser.setInput(is, "utf-8");

      int event = parser.getEventType();

      while (event != XmlPullParser.END_DOCUMENT) {

        switch (event) {

        case XmlPullParser.START_DOCUMENT:

          list = new ArrayList<ClassBean>();

          break;

        case XmlPullParser.START_TAG:

          if ("class".equals(parser.getName())) {

            bean = new ClassBean();

            bean.setId(parser.getAttributeValue(0));

            bean.setName(parser.getAttributeValue(1));

            sList = new ArrayList<StudentBean>();

          } else if ("student".equals(parser.getName())) {

            be = new StudentBean();

            be.setId(parser.getAttributeValue(0));

            be.setName(parser.nextText());

            sList.add(be);

          }

          break;

        case XmlPullParser.END_TAG:

          if ("class".equals(parser.getName())) {

            bean.setList(sList);

            list.add(bean);

            bean = null;

          }

          break;

        }

        event = parser.next();

      }

    } catch (Exception e) {

      e.printStackTrace();

    }

    return list;

  }



  /**

   * 解析test3.xml

   * 

   * @param is

   * @return list

   */

  private List<ClassBean> parseFile3(InputStream is) {

    List<ClassBean> list = null;

    ClassBean bean = null;

    List<StudentBean> sList = null;

    StudentBean be = null;

    try {

      XmlPullParser parser = Xml.newPullParser();

      parser.setInput(is, "utf-8");

      int event = parser.getEventType();

      while (event != XmlPullParser.END_DOCUMENT) {

        switch (event) {

        case XmlPullParser.START_DOCUMENT:

          list = new ArrayList<ClassBean>();

          break;

        case XmlPullParser.START_TAG:

          if ("class".equals(parser.getName())) {

            bean = new ClassBean();

            bean.setId(parser.getAttributeValue(0));

            bean.setName(parser.getAttributeValue(1));

            sList = new ArrayList<StudentBean>();

          } else if ("student".equals(parser.getName())) {

            be = new StudentBean();

            be.setId(parser.getAttributeValue(0));

            sList.add(be);

          } else if ("name".equals(parser.getName())) {

            be.setName(parser.nextText());

          } else if ("sex".equals(parser.getName())) {

            be.setSex(parser.nextText());

          }

          break;

        case XmlPullParser.END_TAG:

          if ("class".equals(parser.getName())) {

            bean.setList(sList);

            list.add(bean);

            bean = null;

          }

          break;

        }

        event = parser.next();

      }

    } catch (Exception e) {

      e.printStackTrace();

    }

    return list;

  }

}

MyAdapter:

package com.home.xmlparsetest;



import java.util.List;

import android.content.Context;

import android.view.Gravity;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseExpandableListAdapter;

import android.widget.LinearLayout;

import android.widget.TextView;



public class MyAdapter extends BaseExpandableListAdapter {

  private List<ClassBean> classList;

  private Context context;



  public MyAdapter(Context context, List<ClassBean> classList) {

    this.context = context;

    this.classList = classList;

  }



  @Override

  public Object getChild(int groupPosition, int childPosition) {

    List<StudentBean> sList = classList.get(groupPosition).getList();

    StudentBean be = null;

    if (sList != null) {

      be = sList.get(childPosition);

    }

    return be;

  }



  @Override

  public long getChildId(int groupPosition, int childPosition) {

    return childPosition;

  }



  @Override

  public View getChildView(int groupPosition, int childPosition,

      boolean isLastChild, View convertView, ViewGroup parent) {

    LinearLayout ll = new LinearLayout(context);

    ll.setOrientation(LinearLayout.HORIZONTAL);

    List<StudentBean> sList = classList.get(groupPosition).getList();



    if (sList != null && sList.size() > 0

        && sList.get(childPosition).getId() != null) {

      TextView tv1 = getTextView2();

      tv1.setText(sList.get(childPosition).getId());

      ll.addView(tv1);

    }



    if (sList != null && sList.size() > 0

        && sList.get(childPosition).getName() != null) {

      TextView tv2 = getTextView2();

      tv2.setText(sList.get(childPosition).getName());

      ll.addView(tv2);

    }



    if (sList != null && sList.size() > 0

        && sList.get(childPosition).getSex() != null) {

      TextView tv3 = getTextView2();

      tv3.setText(sList.get(childPosition).getSex());

      ll.addView(tv3);

    }

    return ll;

  }



  @Override

  public int getChildrenCount(int groupPosition) {

    int size = 0;

    List<StudentBean> sList = classList.get(groupPosition).getList();

    if (sList != null) {

      size = sList.size();

    }

    return size;

  }



  @Override

  public Object getGroup(int groupPosition) {

    return classList.get(groupPosition);

  }



  @Override

  public int getGroupCount() {

    return classList.size();

  }



  @Override

  public long getGroupId(int groupPosition) {

    return groupPosition;

  }



  @Override

  public View getGroupView(int groupPosition, boolean isExpanded,

      View convertView, ViewGroup parent) {

    LinearLayout ll = new LinearLayout(context);

    ll.setOrientation(LinearLayout.HORIZONTAL);

    TextView tv1 = getTextView1();

    tv1.setText(classList.get(groupPosition).getId());

    ll.addView(tv1);



    TextView tv2 = getTextView1();

    tv2.setText(classList.get(groupPosition).getName());

    ll.addView(tv2);

    return ll;

  }



  @Override

  public boolean hasStableIds() {

    return true;

  }



  @Override

  public boolean isChildSelectable(int groupPosition, int childPosition) {

    return true;

  }



  private TextView getTextView1() {

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(

        ViewGroup.LayoutParams.WRAP_CONTENT,

        ViewGroup.LayoutParams.WRAP_CONTENT);

    lp.setMargins(0, 0, 20, 0);

    TextView tv = new TextView(context);

    tv.setLayoutParams(lp);

    tv.setGravity(Gravity.CENTER_VERTICAL);

    tv.setPadding(36, 0, 0, 0);

    tv.setTextSize(25);

    return tv;

  }



  private TextView getTextView2() {

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(

        ViewGroup.LayoutParams.WRAP_CONTENT,

        ViewGroup.LayoutParams.WRAP_CONTENT);

    lp.setMargins(20, 0, 50, 0);

    TextView tv = new TextView(context);

    tv.setLayoutParams(lp);

    tv.setGravity(Gravity.CENTER_VERTICAL);

    tv.setPadding(36, 0, 0, 0);

    tv.setTextSize(18);

    return tv;

  }

}

ClassBean实体类:

package com.home.xmlparsetest;



import java.util.List;



public class ClassBean {

  private String id;

  private String name;

  private List<StudentBean> list;



  public String getId() {

    return id;

  }



  public void setId(String id) {

    this.id = id;

  }



  public String getName() {

    return name;

  }



  public void setName(String name) {

    this.name = name;

  }



  public List<StudentBean> getList() {

    return list;

  }



  public void setList(List<StudentBean> list) {

    this.list = list;

  }



}

StudentBean:

package com.home.xmlparsetest;



public class StudentBean {  private String id;  private String name;  private String sex;  public String getId() {   return id;  }  public void setId(String id) {   this.id = id;  }  public String getName() {   return name;  }  public void setName(String name) {   this.name = name;  }  public String getSex() {   return sex;  }  public void setSex(String sex) {   this.sex = sex;  } }

布局文件main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >



    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal" >



        <Button

            android:id="@+id/main_btn_test1"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="解析test1" />



        <Button

            android:id="@+id/main_btn_test2"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="解析test2" />



        <Button

            android:id="@+id/main_btn_test3"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="解析test3" />

    </LinearLayout>



    <ExpandableListView

        android:id="@+id/list"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" >

    </ExpandableListView>



</LinearLayout>

assets里面的test1.xml:

<?xml version="1.0" encoding="utf-8"?>

<classList>



    <class id="1">一班</class>



    <class id="2">二班</class>



    <class id="3">三班</class>



    <class id="4">四班</class>



</classList>

assets里面的test2.xml:

<?xml version="1.0" encoding="utf-8"?>

<classList>



    <class id="1" name="一班" >

        <student id="1" >张三       </student>

        <student id="2" >李四      </student>

    </class>



    <class id="2" name="二班" >

        <student id="3" >王五</student>

        <student id="4" >赵六</student>

    </class>



    <class id="3" name="三班" >

        <student id="5" >小明</student>

        <student id="6" >小高 </student>

    </class>



    <class id="4" name="四班" >

        <student id="7" >小花</student>

        <student id="8" >小红 </student>

    </class>



</classList>

assets里面的test3.xml:

<?xml version="1.0" encoding="utf-8"?>

<classList>



    <class id="1" name="一班" >

       <student id="1" >

           <name>张三</name>

           <sex></sex>

       </student>

       <student id="2" >

           <name>李四</name>

           <sex></sex>

       </student>

    </class>



    <class id="2" name="二班" >

       <student id="3" >

           <name>王五</name>

           <sex></sex>

       </student>

       <student id="4" >

           <name>赵六</name>

           <sex></sex>

       </student>

    </class>



    <class id="3" name="三班" >

        <student id="5" >

           <name>小明</name>

           <sex></sex>

       </student>

        <student id="6" >

           <name>小高</name>

           <sex></sex>

       </student>

    </class>



    <class id="4" name="四班" >

       <student id="7" >

           <name>小花</name>

           <sex></sex>

       </student>

       <student id="8" >

           <name>小红</name>

           <sex></sex>

       </student>

    </class>



</classList>

http://www.tuicool.com/articles/EZrqEb

你可能感兴趣的:(android)