note 19- SAX and XMLReader and assets folder in android

IBM SAX doc:

http://www.ibm.com/developerworks/cn/xml/x-saxhandle/

 

方法名称 方法说明
public void setDocumentLocator(Locator locator) 设置一个可以定位文档内容事件发生位置的定位器对象
public void startDocument() throws SAXException 用于处理文档解析开始事件
public void endDocument() throws SAXException 用于处理文档解析结束事件
public void startPrefixMapping(java.lang.String prefix, java.lang.String uri) throws SAXException 用于处理前缀映射开始事件,从参数中可以得到前缀名称以及所指向的uri
public void endPrefixMapping(java.lang.String prefix) throws SAXException 用于处理前缀映射结束事件,从参数中可以得到前缀名称
public void startElement(java.lang.String namespaceURI,java.lang.String localName,java.lang.String qName,Attributes atts) throws SAXException 处理元素开始事件,从参数中可以获得元素所在名称空间的uri,元素名称,属性列表等信息
public void endElement(java.lang.String namespaceURI, java.lang.String localName, java.lang.String qName) throws SAXException 处理元素结束事件,从参数中可以获得元素所在名称空间的uri,元素名称等信息
public void characters(char[] ch, int start, int length) throws SAXException 处理元素的字符内容,从参数中可以获得内容
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException 处理元素的可忽略空格
public void processingInstruction(java.lang.String target, java.lang.String data) throws SAXException 处理解析中产生的处理指令事件

 

 

 

 

about asset folder :

 

1.   assets folder won't be registered in the R file . So  it just can be get directly ;

 

2.   get a resource from assets folder: InputStream is = Context.getAssets().open("file_name");  (no           need to be with "/       assets/");

      return an input stream directly;

 

 

 

about res folder :

 

1.   once files put in the res folder , they will be registered (can get by id) , and will be compiled into              binary code .

 

2.  get a resource from the res folder:   Context.getResource().getXXX(R.xxx.xxxx);

       return a Class instance depence on the getXXX function ;

 

       for example:  XmlResourceParser xmlFile=XMLDecoderTest.this.getResources().getXml                            (R.xml.testxml);

 

        so XmlResourceParser has many function to handle the xml binary file;

 

 

 

about XMLReader :

 

1.  a little complicate create :

      instance an SAXParserFactory , and new a SAXParser , and get a XMLReader from SAXParser;

 

      XMLReader reader=SAXParserFactory.newInstance().newSAXParser().getXMLReader();

 

2.  setContentHandler for the XMLReader;

     reader.setContentHandler(new XMLHandler());

 

3.  start parsing :    reader.parse(new InputSource(new StringReader(xmlFile)));

     .parse(InputSource inputsource (StringReader stringReader( String fileString)));

 

4. the XMLHandler extends ContentHandler , override a set of functions . Refer to the IBM doc;

 

 

5.  Remember to set the permission if I want to write it to the SD card;

 

 

 

package com.xml_decoder;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class XMLDecoderTest extends Activity
{
    
    private LinearLayout.LayoutParams layoutParam;
    
    private Button parseButt;
    private LinearLayout ll;
    
    private OnClickListener parseListener=new OnClickListener(){

        public void onClick(View arg0) {
//            throw new UnsupportedOperationException("Not supported yet.");
//            HttpDownloader hd=new HttpDownloader();
//            String result=hd.download("");
//            Log.i("log_filter", "result:"+result);
            
            try{
                
                
//                XmlResourceParser xmlFile=XMLDecoderTest.this.getResources().getXml(R.xml.testxml);
//                
//                SAXParserFactory factory=SAXParserFactory.newInstance();
//                XMLReader reader=factory.newSAXParser().getXMLReader();
//                
//                Log.i("log_filter","xml:"+xmlFile.);
                
                
//                XMLDecoderTest.this.getAssets().open("testxml.xml");
                
                InputStream i=XMLDecoderTest.this.getAssets().open("testxml.xml");
                BufferedReader br=new BufferedReader(new InputStreamReader(i));
                
                StringBuffer sb=new StringBuffer();
                String line;
                
                while((line=br.readLine())!=null){
                    sb.append(line);
                }
                
                String xmlFile=sb.toString();
                
                XMLDecoderTest.this.getAssets().close();
                
                Log.i("log_filter","xml:"+xmlFile);
                
                
                XMLReader reader=SAXParserFactory.newInstance().newSAXParser().getXMLReader();
                
                
                
                reader.setContentHandler(new XMLHandler());
                reader.parse(new InputSource(new StringReader(xmlFile)));
     
            }
            catch(Exception ex){
                Log.e("log_filter", "parse err:"+ex);
            }
        }
    
    };
    
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        ll=new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        
        layoutParam=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        
        parseButt=new Button(this);
        parseButt.setText("parse XML");
        parseButt.setOnClickListener(parseListener);
        
        ll.addView(parseButt, layoutParam);
        
        
        ViewGroup.LayoutParams vlayoutParam=new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT);
        
        
        setContentView(ll,vlayoutParam);
    }
}

 

 

 

 

 

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xml_decoder;

import android.util.Log;
import java.io.IOException;
import java.net.URLConnection;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

/**
 *
 * @author Administrator
 */
public class XMLHandler implements ContentHandler{
    
    
    private StringBuffer sbf=new StringBuffer();
    
    public XMLHandler(){
        
    }

    public void setDocumentLocator(Locator arg0) {
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void startDocument() throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
        Log.i("log_filter","doc start");
    }

    public void endDocument() throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
        Log.i("log_filter","doc end");
    }

    public void startPrefixMapping(String prefix, String uri) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
        Log.i("log_filter","prefix start:"+prefix);
        Log.i("log_filter","uri:"+uri);
        
    }

    public void endPrefixMapping(String arg0) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
        Log.i("log_filter","prefix end");
    }

    public void startElement(String nameSpaceUri, String localName, String qName, Attributes atts) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
        Log.i("log_filter","start element");
        Log.i("log_filter","start element nameSpaceUri:"+nameSpaceUri);
        Log.i("log_filter","start element localName:"+localName);
        Log.i("log_filter","start element qName:"+qName);
        
        for(int i=0;i<atts.getLength();i++){
            Log.i("log_filter","start element attName:"+atts.getValue(i));
        }
    }

    public void endElement(String nameSpaceUri, String localName, String qName) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
        Log.i("log_filter","end element");
        Log.i("log_filter","end element nameSpaceUri:"+nameSpaceUri);
        Log.i("log_filter","end element localName:"+localName);
        
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
        sbf.append(ch, start, length);
        Log.i("log_filter","characters:"+sbf.toString());
        sbf=new StringBuffer();
    }

    public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void processingInstruction(String arg0, String arg1) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void skippedEntity(String arg0) throws SAXException {
//        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}

 

 

 

 

 

 

 

Very weird since the ContentHandler callback system is an asynchronous system and the callback trigger not at the same time .

 

1. If set a tagName as a globel var for catching the element local name . the tagName MUST NOT BE null ,

    when endElement() . But MUST SET TO BE "";

 

2. at the endElement function . DONT USE THE localName to judge, MUST USE qName !

 

 

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xml;

import android.util.Log;
import com.model.Mp3Info;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Administrator
 */
public class Mp3ListContentHandler extends DefaultHandler{
    
    private List<Mp3Info> infos;
    private Mp3Info mp3Info;
    private String tagName="";
    
    
    
    public Mp3ListContentHandler(){
        
    }
    
    public Mp3ListContentHandler(List<Mp3Info> infos){
        this.infos=infos;
    }
    

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        Log.i("l","start doc");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        
        super.startElement(uri, localName, qName, attributes);
        
        this.tagName=localName;
        Log.i("l","current tagName:"+this.tagName);
        if(tagName.equals("source")){
            mp3Info=new Mp3Info();
            Log.i("l","new mp3 insance");
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        
        String temp=new String(ch,start,length);
         
        if(tagName.equals("id")){
            mp3Info.setId(temp);
            Log.i("l","put id"+temp);
        }
        else if(tagName.equals("mp3.name")){
            mp3Info.setMp3Name(temp);
            Log.i("l","put mp3 name  :"+temp);
        }
        else if(tagName.equals("mp3.size")){
            mp3Info.setMp3Size(temp);
            Log.i("l","put mp3 size  :"+temp);
        }
        else if(tagName.equals("lrc.name")){
            mp3Info.setLrcName(temp);
            Log.i("l","put lrc name  :"+temp);
        }
        else if(tagName.equals("lrc.size")){
            mp3Info.setLrcSize(temp);
            Log.i("l","put lrc size  :"+temp);
        }
    }
    
    

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        
        Log.i("l","end doc");
        
        
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        
        Log.i("l","end element:"+qName);
        
        if(qName.equals("source")){
            infos.add(mp3Info);
            Log.i("l","end element. infos:"+infos.toString());
        }
        tagName="";
    }

    
    
    public List<Mp3Info> getInfos() {
        return infos;
    }

    public void setInfos(List<Mp3Info> infos) {
        this.infos = infos;
    }
    
    
}

 

 

 

<?xml version="1.0" encoding="utf-8"?>

<resources>
    
    <source>
        
        <id>0001</id>
        <mp3.name>9Crimes.mp3</mp3.name>
        <mp3.size>5236654</mp3.size>
        <lrc.name>9Crimes.lrc</lrc.name>
        <lrc.size>1381</lrc.size>
        
    </source>
    
    
    
    <source>
        
        <id>0002</id>
        <mp3.name>20Gones.mp3</mp3.name>
        <mp3.size>8190789</mp3.size>
        <lrc.name>20Gones.lrc</lrc.name>
        <lrc.size>1953</lrc.size>
        
    </source>
    
    
    <source>
        
        <id>0003</id>
        <mp3.name>Accidental Babies.mp3</mp3.name>
        <mp3.size>9459086</mp3.size>
        <lrc.name>Accidental Babies.lrc</lrc.name>
        <lrc.size>1969</lrc.size>
        
    </source>
    
    
    <source>
        
        <id>0004</id>
        <mp3.name>Coconut Skin.mp3</mp3.name>
        <mp3.size>5415331</mp3.size>
        <lrc.name>Coconut Skin.lrc</lrc.name>
        <lrc.size>1616</lrc.size>
        
    </source>
    
    
     <source>
        
        <id>0005</id>
        <mp3.name>Dogs.mp3</mp3.name>
        <mp3.size>6028477</mp3.size>
        <lrc.name>Dogs.lrc</lrc.name>
        <lrc.size>1901</lrc.size>
        
    </source>
    
    
    <source>
        
        <id>0006</id>
        <mp3.name>Elephant.mp3</mp3.name>
        <mp3.size>8566325</mp3.size>
        <lrc.name>Elephant.lrc</lrc.name>
        <lrc.size>1637</lrc.size>
        
    </source>
    
    
    <source>
        
        <id>0007</id>
        <mp3.name>Gray Room.mp3</mp3.name>
        <mp3.size>8251602</mp3.size>
        <lrc.name>Gray Room.lrc</lrc.name>
        <lrc.size>1849</lrc.size>
        
    </source>
    
    
    
    <source>
        
        <id>0008</id>
        <mp3.name>Me,My Yoke And I.mp3</mp3.name>
        <mp3.size>8587641</mp3.size>
        <lrc.name>Me,My Yoke And I.lrc</lrc.name>
        <lrc.size>2017</lrc.size>
        
    </source>
    
    
    
    <source>
        
        <id>0009</id>
        <mp3.name>Rootless Tree.mp3</mp3.name>
        <mp3.size>6321481</mp3.size>
        <lrc.name>Rootless Tree.lrc</lrc.name>
        <lrc.size>2693</lrc.size>
        
    </source>
    
    
    <source>
 
        <id>0010</id>
        <mp3.name>Sleep Don't Weep.mp3</mp3.name>
        <mp3.size>31553663</mp3.size>
        <lrc.name>Sleep Don't Weep.lrc</lrc.name>
        <lrc.size>1178</lrc.size>
        
    </source>
    
</resources>

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值