声明:内容大部分参考自网友博客。个人只是做了小小的总结
我个人觉得可以用MVC模式去看待解析xml文件的实现:
下面是具体实现:
首先编写一个xml的数据文件存放在res/raw文件目录下:
<?xml version="1.0" encoding="utf-8"?>
<users>
<beauty>
<name>范冰冰</name>
<age>28</age>
</beauty>
<beauty>
<name>杨幂</name>
<age>23</age>
</beauty>
</users>
1.编写模型代码:
package com.example.sax;
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "美女资料 [年龄=" + age + ", 姓名=" + name + "]";
}
}
package com.example.sax;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
//声明一个装载Beauty类型的List
private ArrayList<User> mList;
//声明一个Beauty类型的变量
private User beauty;
//声明一个字符串变量
private String content;
/**
* MySaxHandler的构造方法
*
* @param list 装载返回结果的List对象
*/
public MyHandler(ArrayList<User> list){
this.mList = list;
}
/**
* 当SAX解析器解析到XML文档开始时,会调用的方法
*/
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
/**
* 当SAX解析器解析到XML文档结束时,会调用的方法
*/
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
/**
* 当SAX解析器解析到某个属性值时,会调用的方法
* 其中参数ch记录了这个属性值的内容
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
content = new String(ch, start, length);
}
/**
* 当SAX解析器解析到某个元素开始时,会调用的方法
* 其中localName记录的是元素属性名
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if("beauty".equals(localName)){
beauty = new User(); //新建Beauty对象
}
}
/**
* 当SAX解析器解析到某个元素结束时,会调用的方法
* 其中localName记录的是元素属性名
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if("name".equals(localName)){
beauty.setName(content);
}else if("age".equals(localName)){
beauty.setAge(content);
}else if("beauty".equals(localName)){
mList.add(beauty); //将Beauty对象加入到List中
}
}
}
2.视图编辑:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/sax"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
3.控制器代码:
package com.example.sax;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.AssetManager;
import android.os.Bundle;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//声明装载Beauty对象的List
private ArrayList<User> beautyList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化beautyList链表
if(beautyList == null){
beautyList = new ArrayList<User>();
}
doMyMission();
setupViews();
}
/**
* 使用SAX解析器解析XML文件的方法
*/
private void doMyMission(){
try {
//获取AssetManager管理器对象
AssetManager as = this.getAssets();
//通过AssetManager的open方法获取到beauties.xml文件的输入流
InputStream is=this.getResources().openRawResource(R.raw.users);//这个是关键,网上代码不会出现
//通过获取到的InputStream来得到InputSource实例
InputSource is2 = new InputSource(is);
//使用工厂方法初始化SAXParserFactory变量spf
SAXParserFactory spf = SAXParserFactory.newInstance();
//通过SAXParserFactory得到SAXParser的实例
SAXParser sp = spf.newSAXParser();
//通过SAXParser得到XMLReader的实例
XMLReader xr = sp.getXMLReader();
//初始化自定义的类MySaxHandler的变量msh,将beautyList传递给它,以便装载数据
MyHandler msh = new MyHandler(beautyList);
//将对象msh传递给xr
xr.setContentHandler(msh);
//调用xr的parse方法解析输入流
xr.parse(is2);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将解析结果输出到界面的方法
*/
private void setupViews(){
String result = "";
for (User b : beautyList) {
result += b.toString();
}
TextView textView = (TextView) findViewById(R.id.sax);
textView.setText(result);
}
}
下面是具体实现:
首先编写一个xml的数据文件存放在res/raw文件目录下:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>liming</name>
<age>30</age>
</person>
<person id="20">
<name>lixiangmei</name>
<age>25</age>
</person>
</persons>
1.编写模型代码:
package com.example.dom;
public class Person {
int id;
String name;
int age;
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setAge(int age)
{
this.age=age;
}
public int getAge()
{
return age;
}
}
package com.example.dom;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Created by zhangmiao on 2016/12/14.
*/
public class AnalyzeDOM {
public static List<Person> readXML(InputStream inputStream) {
List<Person> persons = new ArrayList<>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(inputStream);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("person");
for (int i = 0; i < items.getLength(); i++) {
Person person = new Person();
Element personNode = (Element) items.item(i);
person.setId(new Integer(personNode.getAttribute("id")));
NodeList childNodes = personNode.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node node = childNodes.item(j);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element childNode = (Element) node;
if ("name".equals(childNode.getNodeName())) {
person.setName(childNode.getFirstChild().getNodeValue());
} else if ("age".equals(childNode.getNodeName())) {
person.setAge(new Short(childNode.getFirstChild().getNodeValue()));
}
}
}
persons.add(person);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return persons;
}
}
2.视图编辑:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/dom_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="here"
android:onClick="onClick"/>
</androidx.constraintlayout.widget.ConstraintLayout>
3.控制器代码:
package com.example.dom;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.InputStream;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// private static final String TAG = "AnalyzeXMLDemo";
private TextView mTextView;
private Button dom;
private InputStream inputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
dom = (Button)findViewById(R.id.dom_button);
}
public void onClick(View v) {
String result = "";
inputStream = getResources().openRawResource(R.raw.itcase);
switch (v.getId()) {case R.id.dom_button:
result += "--------- DOM ---------" + "\n";
if (inputStream == null) {
result = "inputStream is null";
} else {
List<Person> personList = AnalyzeDOM.readXML(inputStream);
if (personList != null) {
for (int i = 0; i < personList.size(); i++) {
String message = "id = " + personList.get(i).getId() + " , name = " + personList.get(i).getName()
+ " , age = " + personList.get(i).getAge() + ".\n";
result += message;
}
}
}
mTextView.setText(result);
break;default:
break;
}
}
}