• android 使用Sax 读取xml


    Sax 读取xml ,读取较快,最重要的是占用内存较少.

    为了防止自己遗忘.留下我今天的足迹.也供大家参考.如果有误.请指正.

    首先 在src 根目录下面创建一个Person.xml 文件.里面添加内容:

    1.Person.xml

    View Code
    <?xml version="1.0" encoding="UTF-8"?>
    <persons>
        <person id="23">
            <name>关大爷</name>
            <age>19</age>
        </person>
        <person id="20">
            <name>张飞</name>
            <age>18</age>
        </person>
          <person id="19">
            <name>主公</name>
            <age>20</age>
        </person>
    </persons>

    2.写一个 读取xml的personbean

    Person

    View Code
    package com.example.bean;
    
    public class Person {
        private int _id;
        private String _name;
        private int _age;
        
        public int get_id() {
            return _id;
        }
        public void set_id(int _id) {
            this._id = _id;
        }
        public String get_name() {
            return _name;
        }
        public void set_name(String _name) {
            this._name = _name;
        }
        public int get_age() {
            return _age;
        }
        public void set_age(int _age) {
            this._age = _age;
        }
        /* (non-Javadoc)
         * @see java.lang.Object#toString()
         */
        @Override
        public String toString() {
            return "Person [_id=" + _id + ", _name=" + _name + ", _age=" + _age+ "]";
        }
    
    }

    3.添加一个 personservice 类

    View Code
    package com.example.service;
    
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.DefaultHandler;
    
    import com.example.bean.Person;
    
    import android.R.integer;
    import android.sax.Element;
    import android.sax.EndElementListener;
    import android.sax.RootElement;
    import android.sax.StartElementListener;
    import android.util.Log;
    
    public class SaxService {
        
        private   Person p;
        
        public List<Person> readxml(InputStream stream) throws Throwable, SAXException{
            SAXParserFactory factory=SAXParserFactory.newInstance();
            SAXParser  parser=factory.newSAXParser();
            PersonHander dh=new PersonHander();
             parser.parse(stream, dh);
            return  dh.getPersons();
        }
        
        private class PersonHander extends DefaultHandler{
             private List<Person> persons=null;
             /**
             * @return the persons
             */
            public List<Person> getPersons() {
                return persons;
            }
    
            
            // 读取顺序
            // startDocument()  startElement()  characters(), endElement(), endDocument()
            
            private String pretag=null;
             private Person p=null;
            /* (non-Javadoc)
             * @see org.xml.sax.helpers.DefaultHandler#startDocument()
             */
            @Override
            public void startDocument() throws SAXException {
                persons =new ArrayList<Person>();
            }
            
            /* (non-Javadoc)
             * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
             */
            @Override
            public void startElement(String uri, String localName, String qName,
                    Attributes attributes) throws SAXException {
                if("person".equals(localName)){
                    p=new Person();
                 p.set_id( new Integer(attributes.getValue(0)));
                }
                //此步执行完毕后 会执行 characters(char[] ch, int start, int length)
                pretag=localName; //添加一个表示
            }
            
            
            /* (non-Javadoc)
             * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
             */
            @Override
            public void characters(char[] ch, int start, int length)
                    throws SAXException {
             if(pretag!=null)
             {
                 String data=new String(ch, start, length);
                 if("name".equals(pretag)){
                     p.set_name(data);
                 }else if("age".equals(pretag)){
                     p.set_age(new Integer(data));
                 }
             }
             //继续执行  endElement(String uri, String localName, String qName)
            }
    
            /* (non-Javadoc)
             * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
             */
            @Override
            public void endElement(String uri, String localName, String qName)
                    throws SAXException {
                if("person".equals(localName)){
                    persons.add(p);
                    p=null; 
                }
                
                pretag=null;
                // 清空数据,(多条记录)重复开始执行 startElement(String uri, String localName, String qName,
             }
        }
    }

    4.进行单元测试

    persontest

    View Code
    package com.example.unit;
    
    import java.io.InputStream;
    import java.util.List;
    
    import org.xml.sax.SAXException;
    
    import android.test.AndroidTestCase;
    import android.util.Log;
    
    import com.example.bean.Person;
    import com.example.service.SaxService;
    
    public class persontest  extends AndroidTestCase{
        public void test() throws Throwable, Throwable
        {
            SaxService ss=new SaxService();
            InputStream stream= this.getClass().getClassLoader().getResourceAsStream("Person.xml");
            List<Person> P=    ss.readxml(stream);
            for(Person p : P){
                Log.i("test",   p.toString());
            }
        }
    }

    进行单元测试 需要在配置文件中加入两段代码

    View Code
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.sax_xml"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="15" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <!-- 加入下面这句  -->
             <uses-library android:name="android.test.runner" />
            <activity
                android:name=".MainActivity"
                android:label="@string/title_activity_main" >
                ......
            </activity>
        </application>
           <!-- 加入下面这句  -->
    <instrumentation android:name="android.test.InstrumentationTestRunner"
          android:targetPackage="com.example.sax_xml" android:label="Tests for My App" />
    </manifest>

    运行结果: 

    读取成功.

    源码:https://files.cnblogs.com/xyong/Sax_Xml.rar


    作者:javaoraspx
    出处:http://www.cnblogs.com/xyong/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    Calendar来进行一个时间段内每天的判断
    关于PreparedStatement的setDate的了解
    git学习--创建标签
    git学习--bug分支
    hibernate(1)
    JavaScript(三)---- 控制流程语句
    JavaScript(二)---- 变量、数据类型和运算符
    JavaScript(一)---- 概述
    css(四)-- 盒子模型和定位
    css(三)-- 常用属性
  • 原文地址:https://www.cnblogs.com/xyong/p/2587292.html
Copyright © 2020-2023  润新知