android之xml数据解析(DOM)

 DOM解析是把整个需要解析的xml文件暂存在内存中。

需要解析的XML文档:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="23">
        <name>lee</name>
        <age>30</age>
    </person>
    
    <person id="20">
        <name>leo</name>
        <age>24</age>
    </person>

</persons>  


使用DOM方式解析的java代码: 

package xml;

import java.io.IOException;
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 org.xml.sax.SAXException;

public class DOMForXml {
    
    public static void main(String[] args) {
        //使用DocumentBuilderFactory工厂创建DocumentBuilder对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            //生成DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            //调用完这句后XML文档解析完成,暂存在内存中
            Document document = builder.parse("test.xml");
            //获得根元素
            Element root = document.getDocumentElement();
            //匹配结点,返回结点集
            NodeList personNodes = root.getElementsByTagName("person");
            for(int i=0;i<personNodes.getLength();i++){
                //遍历结点集
                Element personElement = (Element)personNodes.item(i);
                //获得结点上的属性
                String id = personElement.getAttribute("id");
                //输出
                System.out.println("id:"+id);
                //获得该节点下面的子节点
                NodeList personChilds = personElement.getChildNodes();
                //遍历子结点
                for(int j=0;j<personChilds.getLength();j++){
                    //判断当前结点是否是元素类型结点
                    if(personChilds.item(j).getNodeType()==Node.ELEMENT_NODE){
                        Element childElement = (Element)personChilds.item(j);
                        //判断当前结点
                        if(childElement.getNodeName().equals("name")){
                            //获得当前结点对应的值
                            System.out.println("name:"+childElement.getFirstChild().getNodeValue());
                        }else if(childElement.getNodeName().equals("age")){
                            System.out.println("age:"+childElement.getFirstChild().getNodeValue());
                        }
                    }
                }            
            }
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}  

posted on 2012-09-10 10:45  lee0oo0  阅读(3192)  评论(0编辑  收藏  举报