第一种DOM是全部解析出来,消耗内存空间
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!--添加一个按钮 -->
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO!" />
<!-- 添加一个文本框,用于显示结果 -->
<TextView
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
package com.example.domxml;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MainActivity extends AppCompatActivity {
private Button start;
private TextView show;
private String fileName = "fruit.xml";
InputStream inputStream = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView) findViewById(R.id.show);
start = (Button) findViewById(R.id.start);
try {
inputStream = this.getAssets().open(fileName);
} catch (IOException e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String result = "";
result = parse(inputStream);
show.setText(result);
}
});
}
private String parse(InputStream inputStream) {
String result = "";
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = null;
Document document = null;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
try {
document = documentBuilder.parse(inputStream);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Element element = document.getDocumentElement();
NodeList nodeList = element.getElementsByTagName("fruit");
if (nodeList != null && nodeList.getLength() != 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
Element entry = (Element) nodeList.item(i);
result += "name:" +entry.getAttribute("name") + "-->";
result += entry.getTextContent() + "\n";
}
}
return result;
}
}
第二种:SAX解析,占用内存较小
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="SAX解析" />
<ListView
android:id="@+id/listView1"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
</LinearLayout>
实体类
package com.example.saxxml;
public class Student {
long id;
String name;
String speciality;
long qq;
public Student() {
}
public Student(long id, String name, String speciality, long qq) {
this.id = id;
this.name = name;
this.speciality = speciality;
this.qq = qq;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpeciality() {
return speciality;
}
public void setSpeciality(String speciality) {
this.speciality = speciality;
}
public long getQq() {
return qq;
}
public void setQq(long qq) {
this.qq = qq;
}
}
StudentHandler类
package com.example.saxxml;
import android.util.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.List;
public class StudentHandler extends DefaultHandler {
private String preTAG;
private List<Student> list;
private Student student;
public StudentHandler() {
super();
}
public StudentHandler(List<Student> list) {
this.list = list;
}
@Override
public void startDocument() throws SAXException {
Log.i("---->", "文档开始");
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
Log.i("localNmae------>", localName);
preTAG = localName;
if ("student".equals(localName)) {
student = new Student();
student.setId(Long.parseLong(attributes.getValue(0)));
for (int i = 0; i < attributes.getLength(); i++) {
Log.i("attributes----->",String.valueOf(student.getId()));
}
}
super.startElement(uri, localName, qName, attributes);
}
@Override
public void endDocument() throws SAXException {
Log.i("--------------->","文档结束");
super.endDocument();
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
preTAG = "";
if ("student".equals(localName)) {
list.add(student);
Log.i("----------->","一个元素解析完成");
}
super.endElement(uri, localName, qName);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String str;
if ("name".equals(preTAG)) {
str = new String(ch,start,length);
student.setName(str);
Log.i("name=",student.getName());
} else if ("speciality".equals(preTAG)) {
str = new String(ch,start,length);
student.setSpeciality(str);
Log.i("name=",student.getSpeciality());
} else if ("qq".equals(preTAG)) {
str = new String(ch,start,length);
student.setQq(Long.parseLong(str));
Log.i("qq=",String.valueOf(student.getQq()));
}
super.characters(ch, start, length);
}
public List<Student> getList() {
return list;
}
public void setList(List<Student> list) {
this.list = list;
}
}
主类
package com.example.saxxml;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.example.domxml.R;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
public class SaxXml extends AppCompatActivity {
//新建一个按键
private Button button;
//新建一个列表
private ListView listView;
//新建一个数组列表用于存放字符串数组
private ArrayList<String> list = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sax_xml);
button = (Button) findViewById(R.id.btn1);
listView = (ListView) findViewById(R.id.listView1);
button.setOnClickListener(new ButtonListener());
}
class ButtonListener implements View.OnClickListener {
@Override
public void onClick(View view) {
List<Student> students = parseXml();
for (Iterator iterator = students.iterator();
iterator.hasNext(); ) {
Student student = (Student) iterator.next();
list.add(String.valueOf(student.getId()) + " " + student.getName() + " " + student.getSpeciality() + " " + String.valueOf(student.getQq()));
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(SaxXml.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
}
private List<Student> parseXml() {
SAXParserFactory factory = SAXParserFactory.newInstance();
List<Student> students = null;
try {
XMLReader reader = factory.newSAXParser().getXMLReader();
students = new ArrayList<>();
reader.setContentHandler(new StudentHandler(students));
reader.parse(new InputSource(SaxXml.this.getResources().getAssets().open("student.xml")));
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return students;
}
}
第三种:PULL
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="PULL解析" />
<ListView
android:id="@+id/listView1"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
</LinearLayout>
主类
package com.example.pullxml;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.example.domxml.R;
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.Iterator;
import java.util.List;
import xom.supermario.pullxml.Student;
public class PullXml extends AppCompatActivity {
//新建一个按键
private Button button;
//新建一个列表
private ListView listView;
//新建一个数组列表用于存放字符串数组
private ArrayList<String> list = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_xml);
listView = (ListView) findViewById(R.id.listView1);
//为按键绑定监听器
button.setOnClickListener(new ButtonListener());
}
class ButtonListener implements View.OnClickListener {
@Override
public void onClick(View v) {
//将解析后的结果存储到students中
List<xom.supermario.pullxml.Student> students = parserXMl();
// List<Student> students=null;
//枚举数组中的元素
for (Iterator iterator = students.iterator(); iterator.hasNext(); ) {
xom.supermario.pullxml.Student student = (xom.supermario.pullxml.Student) iterator.next();
//将类的内容转换成字符串,依次存储到list中
list.add(String.valueOf(student.getId()) + " " + student.getName() + " " + student.getSpeciality() + " " + String.valueOf((student.getQQ())));
}
//新建一个适配器daapter用于给listview提供数据
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PullXml.this, android.R.layout.simple_list_item_1, list);
//为listview绑定适配器
listView.setAdapter(adapter);
}
}
private List<xom.supermario.pullxml.Student> parserXMl() {
//初始化一个List<student>变量,用于将所有student成员
List<xom.supermario.pullxml.Student> students = null;
//初始化一个student变量,用于存储每一个节点的信息
xom.supermario.pullxml.Student stu = null;
try {
InputStream inputStream = PullXml.this.getResources().getAssets().open("student.xml");
XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser pullParser = parserFactory.newPullParser();
pullParser.setInput(inputStream, "UTF-8");
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
Log.e("yuan--->event", eventType + "");
//用于存储节点名称
String localName = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
students = new ArrayList<>();
Log.e("yuan", "start document!");
break;
case XmlPullParser.START_TAG:
localName = pullParser.getName();
if ("student".equals(pullParser.getName())) {
stu = new Student();
stu.setId(Long.parseLong(pullParser.getAttributeName(0)));
Log.i("yuans", stu.getId() + " ");
} else if (stu != null) {
//声明一个变量用于存储节点文本
String currentData = null;
if ("name".equals(pullParser.getName())) {
currentData = pullParser.nextText();
stu.setName(currentData);
}else if ("speciality".equals(pullParser.getName())) {
currentData = pullParser.nextText();
stu.setSpeciality(currentData);
} else if ("qq".equals(pullParser.getName())) {
currentData = pullParser.nextText();
stu.setQQ(Long.parseLong(currentData));
}
}
break;
case XmlPullParser.END_TAG:
localName = pullParser.getName();
Log.e("yuans",localName);
if ("student".equals(localName) && stu != null) {
students.add(stu);
stu = null;
}
break;
default:
break;
}
eventType = pullParser.next();
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return students;
}
}