xml sax

package com.knox.musicplayer.util.io;


import java.io.IOException;
import java.io.InputStream;


import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


import android.os.Handler;
import android.os.Message;


import com.knox.musicplayer.entity.Music;


public class MusicXmlParser {


private Handler mHandler;
public static final int END_ELEMENT = 1;
public static final int END_DOCUMENT = 2;
public static final int PARSER_DELAYED = 3;

public MusicXmlParser(Handler handler) {
this.mHandler = handler; 
}

public void parse(InputStream is) throws ParserConfigurationException, SAXException, IOException{
if(is!=null){
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(is, new MusicDefaultHandler());
}
}


private class MusicDefaultHandler extends DefaultHandler {


private Music music;
private String tag;

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


@Override
public void endDocument() throws SAXException {
super.endDocument();
if(mHandler!=null){
mHandler.sendEmptyMessage(END_DOCUMENT);
}
}


@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
tag = localName;
if("music".equals(localName)){
music = new Music();
music.setId(Long.parseLong(attributes.getValue("id")));
}
}


@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
tag = null;
if("music".equals(localName)){
if(mHandler!=null){
Message msg = Message.obtain(mHandler);
msg.what = END_ELEMENT;
msg.obj = music;
msg.sendToTarget();
}
}
}


@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String str = new String(ch, start, length);
if ("name".equals(tag)) {
music.setDisplayName(str);
} else if ("singer".equals(tag)) {
music.setArtist(str);
} else if ("albumpic".equals(tag)) {
music.setAlbumPath(str);
} else if ("musicpath".equals(tag)) {
music.setData(str);
} else if ("time".equals(tag)) {
music.setDuration(Long.parseLong(str));
}
}


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值