Android解析xml(2)---DOM解析

DOM是一种用于xml文档的对象模型,可直接访问xml文档的各个部分。在DOM中,文档被模拟为树状,xml的每个组成部分都被表示为一个节点。DOM允许用户便利文档树,从父节点移动到子节点和兄弟节点等。由于DOM的实现要将xml节点保存在内存中,因此在处理较大的文档时,效率比较低下。

采用DOM解析的方式有点在于它可以进行遍历,可以知道上、下层节点的情况。

本篇文章与上篇Android解析xml(1)—SAX解析不同的地方就是StudyParser中的内容,其余可参考上篇文章。

StudyParser.java

public class StudyParser {
    public static Study parse(InputStream is) {
        Study study = null;
        try {
            study = new Study();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(is);

            //获得根元素<record>
            Element root = document.getDocumentElement();
            NodeList list = root.getElementsByTagName(Study.STUDY);
            for(int i = 0; i < list.getLength(); i++){
                //获得当前节点
                Node curNode = list.item(i);
                study.mId = Integer.parseInt(((Attr)(curNode.getAttributes().item(i))).getValue());

                //获得<study>节点中的所有子节点
                NodeList listChilds = curNode.getChildNodes();
                for(int j = 0; j < listChilds.getLength(); j++){
                    Node child = listChilds.item(j);

                    //如果这个节点是Element类型
                    if(child.getNodeType() == Node.ELEMENT_NODE){
                        //获得元素名
                        String childName = child.getNodeName();
                        //获得文本节点内容
                        String childValue = ((Element)child).getTextContent();
                        //String childValue = child.getFirstChild().getNodeValue();

                        //如果标签是<topic>
                        if(Study.TOPIC.equalsIgnoreCase(childName)){
                            study.mTopic = childValue;
                        }
                        //如果标签是<content>
                        else if(Study.CONTENT.equalsIgnoreCase(childName)){
                            study.mContent = childValue;
                        }
                        //如果标签是<author>
                        else if(Study.AUTHOR.equalsIgnoreCase(childName)){
                            study.mAuthor = childValue;
                        }
                        //如果标签是<date>
                        else if(Study.DATE.equalsIgnoreCase(childName)){
                            study.mDate = childValue;
                        }
                    }
                }
            }

        } catch(Exception ex) {
            Log.d("XML", "StudyParser: parse() failed");
            study = null;
        }
        return study;
    }
}

源码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值