• (DOM解析xml )Android中的XML解析与生成
    时间:2011-12-20?? 作者:佚名?? 出处:互联网

    DOM解析XML文件时,会将XML文件的所有内容以对象树方式存放在内存中,然后允许您使用DOM API遍历XML树、检索所需的数据。使用DOM操作XML的代码看起来比较直观,并且,在某些方面比基于SAX的实现更加简单。但是,因为DOM需要将XML文件的所有内容以对象树方式存放在内存中,所以内存的消耗比较大,特别对于运行Android的移动设备来说,因为设备的资源比较宝贵,所以建议还是采用SAX来解析XML文件,当然,如果XML文件的内容比较小采用DOM是可行的。

    创建DOMPersonService类

    public class DOMPersonService {?
    ?????
    ??? public static List getPersonList(InputStream inStream) throws Exception{?
    ?????????
    ??????? List personList = new ArrayList();?
    ?????????
    ??????? DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();?
    ??????? DocumentBuilder? builder? = factory.newDocumentBuilder();?
    ??????? Document document = builder.parse(inStream);?
    ?????????
    ??????? //注意,此时xml文件已经都被装入内存中的document对象里了???????
    ?????????
    ??????? //取得根结点(元素节点)?
    ??????? Element root = document.getDocumentElement();???
    ?????????
    ??????? NodeList nodes = root.getElementsByTagName("person");?
    ?????????
    ??????? for(int i=0; i
    ??????????? Element personElement = (Element) nodes.item(i);?
    ?????????????
    ??????????? Person person = new Person();?
    ??????????? //为person添加id属性值?
    ??????????? person.setId(Integer.valueOf(personElement.getAttribute("id")));?
    ?????????????
    ??????????? NodeList childNodes = personElement.getChildNodes();?
    ?????????????
    ??????????? //遍历孩子节点,忽略文本节点,保留并处理元素节点?
    ??????????? for(int j=0; j
    ??????????????? Node childNode = childNodes.item(j);?
    ??????????????? if(childNode.getNodeType() == Node.ELEMENT_NODE){?
    ??????????????????? if("name".equals(childNode.getNodeName() )){?
    ??????????????????????? person.setName(childNode.getFirstChild().getNodeValue());?
    ??????????????????? }else if("age".equals(childNode.getNodeName())){?
    ??????????????????????? Text textNode = (Text) childNode.getFirstChild();?
    ??????????????????????? String ageStr = textNode.getNodeValue();?
    ??????????????????????? person.setAge(Integer.valueOf(ageStr));?
    ??????????????????? }?
    ??????????????? }?
    ??????????? }????????????
    ??????????? personList.add(person);??????????
    ??????? }????????
    ??????? return personList;?
    ??? }?

    测试方法

    public void testDOM() throws Throwable {?
    ??????? List personList = null;?
    ??????? InputStream inStream = this.getClass().getClassLoader()?
    ??????????????? .getResourceAsStream("person_list.xml");?
    ??????? personList = DOMPersonService.getPersonList(inStream);?
    ?
    ??????? Log.i("TAG", personList.toString());?
    ??? }?

    网友留言/评论

    我要留言/评论