Dom方式使用的是文档对象模型解析,它首先要将xml文件整个读入内存中,然后再来构建Dom对象,在DOM对象里,xml文件中的所有元素都可以当做节点(Node)对象来处理。这种方式优点是方便对文档进行增加、删除、修改、添加等操作,缺点是它首先要将整个文件读入内存中在解析,如果文件大。会很消耗内存,并且它的执行速度慢。
在android中解析文件是一个三步过程:
(1)创建DocumentBuilderFactory,该对象创建DocumentBuilder
(2)创建DocumentBuilder,DocumentBuilder将实际进行解析以创建Document对象
(3)解析该文件以创建Document对象
//1.解析器工厂类:DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//2.解析器:DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
//3.文档树模型Document
Document document = builder.parse(isStream);
1.把解析的person.xml文件放在src目录下
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="1">
<name>olay</name>
<age>23</age>
</person>
<person id="2">
<name>qiu</name>
<age>21</age>
</person>
<person id="3">
<name>james</name>
<age>23</age>
</person>
<person id="4">
<name>kobe</name>
<age>21</age>
</person>
</persons>
2.针对从xml中获取的信息,需要对其新建一个Person类,存放相关信息
package cn.com.entity;
public class Person {
private Integer id;
private String name;
private int age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "id="+id+",name="+name+",age="+age;
}
}
3.编写DomPersonService的业务代码,解析xml
package com.service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cn.com.entity.Person;
public class DOMPersonService {
public static List<Person> getPersons(InputStream is) throws Exception{
List<Person> persons = new ArrayList<Person>();
//1.解析器工厂类:DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//2.解析器:DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
//3.文档树模型Document
Document document = builder.parse(is);
//元素类Element
Element root = document.getDocumentElement();
// 获取persons根节点中所有的person节点对象
NodeList personNodes = root.getElementsByTagName("person");
// 遍历所有的person节点
for(int i=0;i<personNodes.getLength();i++){
// 根据item(index)获取该索引对应的节点对象
Element personElement = (Element) personNodes.item(i);
// 设置id属性值
int id = new Integer(personElement.getAttribute("id"));
Person person = new Person();
person.setId(id);
// 获取person的仔节点
NodeList childNodes = personElement.getChildNodes();
// 遍历person的仔节点
for(int y=0;y<childNodes.getLength();y++){
// 判断node节点是否是元素节点
if(childNodes.item(y).getNodeType()==Node.ELEMENT_NODE){
//判断元素节点是否是name元素节点
if("name".equals(childNodes.item(y).getNodeName())){
//返回第一个子女的值
String name = childNodes.item(y).getFirstChild().getNodeValue();
person.setName(name);
}else if("age".equals(childNodes.item(y).getNodeName())){//判断元素节点是否是age元素节点
String age =childNodes.item(y).getFirstChild().getNodeValue();
person.setAge(Integer.valueOf(age));
}
}
}
persons.add(person);
}
is.close();//关闭输入流
return persons ;
}
}
4.执行解析代码
MainActivity.java
package com.example.dmo_parser;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.service.DOMPersonService;
import cn.com.entity.Person;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
private ListView listView =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
}
public void onClick(View view) throws Exception{
List<Person> persons=readXml() ;
List<Map<String,String>> data = new ArrayList<Map<String,String>>();
for(Person person:persons){
Map<String,String> map = new HashMap<String, String>();
map.put("name", person.getName());
map.put("age",""+person.getAge());
data.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.person_main,
new String[]{"name","age"}, new int[]{R.id.name,R.id.age});
listView.setAdapter(adapter);
}
public List<Person> readXml() throws Exception{
//加载需要解析的文件。因为XML文件放在src目录下,所以通过类装载器的方式获得文件路径,再以输入流的方式放入解析器
InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("person.xml");
List<Person> persons =DOMPersonService.getPersons(inputStream);
return persons;
}
}
5.布局文件
ctivity_main.xml
<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:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="DOM解析XML"
android:onClick="onClick"
/>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Person_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<View
android:layout_width="25dp"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年龄:" />
<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
效果: