布局文件 layout
Students.xml
<?xml version="1.0" encoding="utf-8"?>
<students>
<student>
<name sex="man">小明</name>
<nickname>明明</nickname>
</student>
<student>
<name sex="woman">小红</name>
<nickname>红红</nickname>
</student>
</students>
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_dom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DOM解析"/>
<TextView
android:id="@+id/tv_dom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="DOM解析结果:" />
<Button
android:id="@+id/btn_sax"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAX解析"/>
<TextView
android:id="@+id/tv_sax"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="SAX解析结果:"/>
</LinearLayout>
MainActivity.java
package com.example.ch11xmlanalyzedemo;
import androidx.appcompat.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.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class MainActivity extends AppCompatActivity {
private Button btnDom;
private TextView tvDom;
private Button btnSax;
private TextView tvSax;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
setListener();
}
private void findViews() {
btnDom = findViewById(R.id.btn_dom);
tvDom = findViewById(R.id.tv_dom);
btnSax = findViewById(R.id.btn_sax);
tvSax = findViewById(R.id.tv_sax);
}
private void setListener() {
MyClickListener listener = new MyClickListener();
btnDom.setOnClickListener(listener);
btnSax.setOnClickListener(listener);
}
class MyClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
String file =
getFilesDir().getAbsolutePath() + "/students.xml";
switch (view.getId()) {
case R.id.btn_dom:
analyzeXmlByDOM(file);
break;
case R.id.btn_sax:
analyzeXmlBySAX(file);
break;
}
}
}
private void analyzeXmlBySAX(String file) {
try {
SAXParserFactory saxFactory =
SAXParserFactory.newInstance();
SAXParser parser = saxFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
MySaxHander hander = new MySaxHander(tvSax);
reader.setContentHandler(hander);
InputSource is =
new InputSource(new FileInputStream(file));
reader.parse(is);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void analyzeXmlByDOM(String file) {
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(file));
NodeList nodes = document.getElementsByTagName("student");
List<Student> list = new ArrayList<>();
for(int i = 0; i < nodes.getLength(); i++){
Student student = new Student();
Node node = nodes.item(i);
NodeList childNodes = node.getChildNodes();
for(int j = 0; j < childNodes.getLength(); j++){
Node childNode = childNodes.item(j);
String nodeName = childNode.getNodeName();
switch (nodeName){
case "name"://获取属性值、节点值
String name = childNode.getTextContent();
NamedNodeMap attrs = childNode.getAttributes();
String sex = attrs.item(0).getTextContent();
student.setName(name);
student.setSex(sex);
break;
case "age":
String content = childNode.getTextContent();
int age = Integer.parseInt(content);
student.setAge(age);
break;
}
}
list.add(student);
}
tvDom.setText("DOM解析结果:" + list.toString());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MySaxHandler.java
package com.example.ch11xmlanalyzedemo;
import android.content.Context;
import android.widget.TextView;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
public class MySaxHandler extends DefaultHandler {
private List<Student> list;
private String content;
private Student student;
private TextView tvSax;
public MySaxHandler(TextView tvSax) {
this.tvSax = tvSax;
}
public MySaxHandler() {
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
list = new ArrayList<>();
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
tvSax.setText("SAX解析结果:" + list.toString());
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
switch (qName){
case "student":
student = new Student();
break;
case "name":
String sex = attributes.getValue("sex");
student.setSex(sex);
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
switch (qName){
case "name":
student.setName(content);
content = "";
break;
case "age":
int age = Integer.parseInt(content);
student.setAge(age);
content = "";
break;
case "student":
list.add(student);
content = "";
break;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
content = new String(ch, start, length);
}
}
Student.java
package com.example.ch11xmlanalyzedemo;
public class Student {
private String name;
private String sex;
private int age;
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}