package com.anjoyo.cnblogs.parse;
import java.io.IOException;
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.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.anjoyo.cnblogs.bean.News;
public class ParseNews extends DefaultHandler{
private List<News> newsList = null;
private News news = null;
private String preTag = null;
private boolean isNews = false;
public List<News> getNewsList(String data) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = null;
try {
parser = factory.newSAXParser();
parser.parse(data, this);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("Tag", newsList.size() + "");
return this.getNewsList();
}
public List<News> getNewsList() {
return this.newsList;
}
public void startDocument() throws SAXException {
super.startDocument();
newsList = new ArrayList<News>();
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName != null && qName.equals("entry")) {
news = new News();
isNews = true;
}
preTag = qName;
}
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
String content = new String(ch,start,length);
Log.i("Tag", preTag);
if(preTag != null && isNews) {
if("id".equals(preTag)) {
news.setId(content);
}else if("title".equals(preTag)) {
Log.i("Tag", content);
news.setTitle(content);
}else if("summary".equals(preTag)) {
Log.i("Tag", content);
news.setSummary(content);
}else if("published".equals(preTag)) {
news.setTime(content);
}else if("views".equals(preTag)) {
news.setViewNum(Integer.parseInt(content));
}else if("comments".equals(preTag)) {
news.setCommentNum(Integer.parseInt(content));
}else if("sourceName".equals(preTag)) {
news.setSource(content);
}
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(qName != null && qName.equals("entry")) {
newsList.add(news);
news = null;
isNews = false;
}
preTag = null;
}
public void endDocument() throws SAXException {
super.endDocument();
}
}