XML解析之sax解析
SAX有一个固定的方法
private void doMyMission(){
try {
InputStream is = this.getAssets().open("songci300.mp3");
InputSource is2 = new InputSource(is);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
Mysongci msh = new Mysongci(nodeList);
xr.setContentHandler(msh);
xr.parse(is2);
} catch (Exception e) {
e.printStackTrace();
}
}
注:这里面的代码在每次XML解析中都基本是一样
首先XML解析需要创建几个类,一个类用于数据的封装,一个类时用于获取XML中的内容。
封装的类就不多说了,我来说下另一个:
public class Mysongci extends DefaultHandler{
private ArrayList<Node> mList;
private Node node;
private String content;
public Mysongci(ArrayList<Node> list){
this.mList = list;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
//获得标签中的文本
content = new String(ch, start, length);
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if("node".equals(localName)){
node = new Node();
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if("title".equals(localName)){
node.setTitle(content);
}else if("auth".equals(localName)){
node.setAuth(content);
}else if("desc".equals(localName)){
node.setDesc(content);
}else if("node".equals(localName)){
mList.add(node);
}
}
}
这个类大部分代码基本都是固定的方法,大家每次用的时候只用改变一些名称就可以通用了.其中Node为封装的类名。