android解析XML的三種方式 DOM、SAX、PULL
阿新 • • 發佈:2018-11-19
第一種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;
}
}