首页 > 代码库 > android如何使用DOM来解析XML文件

android如何使用DOM来解析XML文件

对于以下的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<books>  
    <book email="zhoujunhui">  
        <name>rjzjh</name>  
        <price>jjjjjj</price>  
    </book>  
     <book email="aaaaaaaaa">  
        <name>bbbb</name>  
        <price>ccc</price>  
    </book>  
</books>  

这样来解析:

import java.util.ArrayList;

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 android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;

public class TestActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		XmlReader();
		for(int i=0;i<list.size();i++) {
			Book book = list.get(i);
			Log.d("TAG", "name="+book.name+"email="+book.email);
		}
	}


	public void XmlReader() {
		Document doc = null;
		AssetManager assetManager = this.getAssets();
		DocumentBuilder docBuilder = null;
		DocumentBuilderFactory docBuilderFactory = null;
		try {
			docBuilderFactory = DocumentBuilderFactory.newInstance();
			docBuilder = docBuilderFactory.newDocumentBuilder();
			doc = docBuilder.parse(assetManager.open("test1.xml"));
			Element root = doc.getDocumentElement();
			NodeList books = root.getChildNodes();
			if (books != null) {
				for (int i = 0; i < books.getLength(); i++) {
					Node book = books.item(i);
					Book mybook = null;
					if (book.getNodeType() == Node.ELEMENT_NODE) {
						//这里才表示这个是<book>节点
						mybook = new Book();
						String email = book.getAttributes()
								.getNamedItem("email").getNodeValue();
						mybook.email = email;
						
						for (Node node = book.getFirstChild(); node != null; node = node
								.getNextSibling()) {
							
							if (node.getNodeType() == Node.ELEMENT_NODE) {
								if (node.getNodeName().equals("name")) {
									String name1 = node.getFirstChild()
											.getNodeValue();
									mybook.name = name1;
								}
								if (node.getNodeName().equals("price")) {
									String price = node.getFirstChild()
											.getNodeValue();
									mybook.price = price;
								}
							}
							
						}
						
						list.add(mybook);
					}
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	private ArrayList<Book> list = new ArrayList<Book>();
	
	private class Book{
		String email;
		String name;
		String price;
	}