我们要解析的XML文档:
[html]
<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="1">
<name>crazy in Android</name>
<age>65.5</age>
</book> www.zzzyk.com
<book id="15">
<name>think in java</name>
<age>86.9</age>
</book>
</books>
建一个工程:Android_XML_DOM
工程目录结构:
Book.java
[html]
package com.dom.bean;
public class Book {
private int id;
private String name;
private String price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
BookService.java
[html]
package com.dom.service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.dom.bean.Book;
public class BookService {
public BookService() {
}
public static List<Book> getBooks(InputStream inputStream) throws Exception{
List<Book> list = new ArrayList<Book>();
//创建一个document解析的工厂
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream); //表示整个文档对象
Element element = document.getDocumentElement();
//遍历所有元素
NodeList bookNodes = element.getElementsByTagName("book");
for(int i=0;i<bookNodes.getLength();i++){
Element bookElement = (Element)bookNodes.item(i);
Book book = new Book();
book.setId(Integer.parseInt(bookElement.getAttribute("id")));
NodeList childNodes = bookElement.getChildNodes(); //获取根节点下的子节点
for(int j=0;j<childNodes.getLength();j++){
if(childNodes.item(j).getNodeType() == Node.ELEMENT_NODE){
if("name".equals(childNodes.item(j).getNodeName())){
book.setName(childNodes.item(j).getFirstChild().getNodeValue());
}else if("age".equals(childNodes.item(j).getNodeName())){
book.setPrice(childNodes.item(j).getFirstChild().getNodeValue());
}
}
}
list.add(book);
}
return list;
}
}
BookServiceTest.java
[html]
package com.dom.test;
import java.io.InputStream;
import java.util.List;
import com.dom.bean.Book;
import com.dom.service.BookService;
import android.test.AndroidTestCase;
import android.util.Log;
public class BookServiceTest extends AndroidTestCase{
private static final String TAG = "BookServiceTest";
public void testBook(){
InputStream xml = this.getClass().getClassLoader().getResourceAsStream("book.xml");
List<Book> books;
try {
books = BookService.getBooks(xml);
for(Book book:books){
Log.i(TAG, book.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行测试方法之后,Logcat日志输出信息如下: