android DOM、 SAX 、PULL 解析XML---练习

主要推荐使用SAX和PULL
SAX解析的特点:
这种解析方法速度快、占用内存少,但是它需要应用程序自己处理解析器的状态,实现起来会比较麻烦,而且它只支持对XML文件的读取,不支持写入。
SAX解析器的工作方式是自动将事件推入注册的事件处理器进行处理,因此我们不能控制事件的处理主动结束。
SAX解析是事件驱动的,它不会将整个文档读入内存再解析,而是在读取文档的过程中就会遍历完毕文档中所有的节点解析它,当我们在解析XML文件时,如果只需要文档前边或是中间一小部分数据,使用SAX解析就浪费了处理器资源,这时我们使用PULL解析就非常合适了。

PULL解析:应用程序根据自己的需要控制解析器的读取。这种方式 继承了SAX解析速度快、占用内存少等优点,同时它也保持了接口简单、编程容易等特点。PULL解析器的工作方式为允许应用程序代码主动从解析器中获取事件,正因为是主动获取事件,因此可以在满足了需要的条件后不再获取事件,结束解析。

使用SAX解析,在解析器解析过程中通过回调把TAB/VALUE值等传给我们,我们可以直接拿到这些值进行比较、处理。而PULL的原理是它只告诉我们一个TAG开始或者结束了,至于TAG/VALUE的值是什么需要我们自己去向解析器问,所以叫做PULL(拉),而SAX看起来是PUSH(推)给我们的。
SAX与PULL之间的区别,PULL是使用一个循环结构,循环体中我们可以随时跳出(break),而SAX不是,SAX是只要开始解析了,就必须解析完成。所以PULL的使用比SAX会更加灵活,在Android的开发中,更推荐使用PULL解析XML。

以上参考:http://m.blog.csdn.net/article/details?id=46831253
下面为则是个人测试代码:
在Java端将数据转为xml的形式 jsp文件中:

<?xml version="1.0" encoding="UTF-8" ?><%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><fqs><c:forEach items="${fqs}" var="fq">
            <fq name="${fq.name}">
                <content>${fq.content}</content>
                <time>${fq.time}</time>
            </fq>
    </c:forEach>
    </fqs>

在android端获取XML数据:


public void getXml(View view){
     String path="http://192.168.43.135:8080/G150725_S2SH/fqActiongetXML.action";
     try {
         //实例化URL 定义网络数据路径
         URL url=new URL(path);
         //打开连接
       HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
       //设置请求方式
         httpURLConnection.setRequestMethod("GET");
         //设置连接超时的时间
         httpURLConnection.setConnectTimeout(5000);
         //获取响应码
         int code=httpURLConnection.getResponseCode();
         if(code==200){//得到数据响应
             //获取数据
             InputStream is=httpURLConnection.getInputStream();
             //测试:打印看是否是所需数据
             String str="";
             BufferedReader br=new BufferedReader(new InputStreamReader(is));
             while((str=br.readLine())!=null){
                 Log.i("hhhhhh",str);
             }
         }

         //解析XML :DOM   SAX  PULL(android有的)

     } catch (MalformedURLException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }

 }

一、用DOM解析:一次性取出全部的数据进行解析,若数据量多则不建议使用;以下为基础的原码,也可第三方使用DOM4J,使用时代码量少,使用方便。


  try {
         DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
             DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
             Document document=documentBuilder.parse(is);
             //获取标签
             Element root=document.getDocumentElement();
             Log.i("hhhhhhh","root:"+root.getTagName());
             NodeList nodeList=root.getElementsByTagName("fq");
             for (int i=0;i<nodeList.getLength();i++){
                 Element element= (Element) nodeList.item(i);
                 //获取属性name
                 String name=element.getAttribute("name");
                 //获取子标签
                 Element elementC=(Element)element.getElementsByTagName("content").item(0);
                 String ciontent=elementC.getTextContent();
                 Element elementT= (Element) element.getElementsByTagName("time").item(0);
                 String time=elementT.getTextContent();
                 Log.i("hhhhhhh",name+"   "+time);

             }
         } catch (ParserConfigurationException e) {
             e.printStackTrace();
         } catch (SAXException e) {
             e.printStackTrace();
         }

二、SAX :


//sax
         try {
         SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
             SAXParser saxParser=saxParserFactory.newSAXParser();
            saxParser.parse(is,new DefaultHandler(){
                @Override
                public void startDocument() throws SAXException {
                    super.startDocument();
                }

                @Override
                public void endDocument() throws SAXException {
                    super.endDocument();
                }

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    super.startElement(uri, localName, qName, attributes);
                    //开始标签
                    local = localName;
                    if("fq".equals(localName)){
                        fq = new FQ();
                        String name=attributes.getValue(0);
                        fq.setName(name);
                    }

                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    super.endElement(uri, localName, qName);
                    //结束标签
                    local=null;//小细节
                    if ("fq".equals(localName)){
                        fqs.add(fq);
                    }
                }

                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    super.characters(ch, start, length);
                    //文本内容 包括结束标签和下一个开始标签之间的换行 为空而全局变量不会仍然可能为 content 会导致下面的取值为空 所以在借宿标签中把local=null;
                    if ("content".equals(local)){
                        String content=new String(ch,start,length);
                        fq.setContent(content);
                    }else if ("time".equals(local)){
                        String time=new String(ch,start,length);
                        fq.setTime(time);
                    }
                }
            });
         } catch (ParserConfigurationException e) {
             e.printStackTrace();
         } catch (SAXException e) {
             e.printStackTrace();
         }

三、pull解析:

 //PULL
         try {
         XmlPullParser pullParser= Xml.newPullParser();
             pullParser.setInput(is,"UTF-8");
             //得到事件类型  开始文档
             int type=pullParser.getEventType();
             //不等于结束
             while(type!=XmlPullParser.END_DOCUMENT){
                 switch (type){
                     case XmlPullParser.START_TAG:
                         //获取开始标签的名字
                         String startTagName=pullParser.getName();
                         if("fq".equals(startTagName)){
                             fq = new FQ();
                             String name=pullParser.getAttributeValue(0);
                             fq.setName(name);
                         }else if("content".equals(startTagName)){
                             String content= pullParser.nextText();
                             fq.setContent(content);
                         }else if("time".equals(startTagName)){
                             String time= pullParser.nextText();
                             fq.setTime(time);
                         }
                         break;
                     case XmlPullParser.END_TAG:
                         //获取结束标签的名字
                         String endTagName=pullParser.getName();
                         if("fq".equals(endTagName)){
                             fqs.add(fq);
                         }
                         break;
                 }
                 //下一个
                 type=pullParser.next();
             }
         } catch (XmlPullParserException e) {
             e.printStackTrace();
         }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值