public class Mp3ListContentHandler extends DefaultHandler {
private List<Mp3Info> infos = null;
private Mp3Info mp3Info = null;
private String tagName = null;
public Mp3ListContentHandler(List<Mp3Info> infos) {
super();
this.infos = infos;
}
public List<Mp3Info> getInfos() {
return infos;
}
public void setInfos(List<Mp3Info> infos) {
this.infos = infos;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String temp = new String(ch, start, length);
if(tagName.equals("id")){
mp3Info.setId(temp);
}else if(tagName.equals("mp3.name")){
mp3Info.setMp3Name(temp);
}else if(tagName.equals("mp3.size")){
mp3Info.setMp3Size(temp);
}else if(tagName.equals("lrc.name")){
mp3Info.setLrcName(temp);
}else if(tagName.equals("lrc.size")){
mp3Info.setLrcSize(temp);
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
tagName = " "; //预防出错
if(localName.equals("resource")){ //qname为空,设置成localName
infos.add(mp3Info);
}
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tagName = localName;
if(tagName.equals("resource")){
System.out.println("tagName == resource");
mp3Info = new Mp3Info();
}
super.startElement(uri, localName, qName, attributes);
}
}
xml解析:
private List<Mp3Info> parse(String xmlStr) { // 解析xml
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
List<Mp3Info> infos = new ArrayList<Mp3Info>();
try {
XMLReader Reader = saxParserFactory.newSAXParser().getXMLReader();
Mp3ListContentHandler mp3ListContentHandler = new Mp3ListContentHandler(infos);
Reader.setContentHandler(mp3ListContentHandler); //设置handler
Reader.parse(new InputSource(new StringReader(xmlStr)));
for (Iterator iterator = infos.iterator(); iterator.hasNext();) {
Mp3Info mp3Info = (Mp3Info) iterator.next();
System.out.println(mp3Info);
}
} catch (Exception e) {
e.printStackTrace();
}
return infos;
}