我試圖使用SAX解析器SAX RSS FEED解析器
這是我的代碼來解析一個RSS提要:
public class MainActivity extends Activity {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ListView list;
ArrayList<String> sinlgeItem = null;
ProgressDialog pd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView)findViewById(R.id.list);
boolean b=parseData();
Log.v("result", "value"+b);
for(int i=0;i<data.size();i++){
Log.e("ITEM",data.get(i).get(0)+"__"+data.get(i).get(1));
}
}
/**
* method parse the data
*/
private boolean parseData() {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL url = new URL("https://itunes.apple.com/WebObjects/MZStore.woa/wpa/MRSS/newreleases/sf=143441/limit=25/rss.xml");
xr.setContentHandler(new MyHandler());
xr.parse(new InputSource(url.openStream()));
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public class MyHandler extends DefaultHandler{
Boolean ITEM=false;
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
super.endElement(uri, localName, name);
if (ITEM){
RootElement root=new RootElement("rss");
Element chan=root.getChild("channel");
Element itms=chan.getChild("item");
Element title=itms.getChild("title");
Element artist=itms.getChild("http://phobos.apple.com/rss/1.0/modules/itms/", "artist");
title.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
sinlgeItem.add(body);
Log.v("title",body);
}
});
artist.setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
sinlgeItem.add(body);
Log.v("artist", body);
}
});
ITEM=false;
data.add(sinlgeItem);
}
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equals("item")){
sinlgeItem = new ArrayList<String>();
ITEM=true;
}
}
}
}
這是鏈接到XML提要 https://itunes.apple.com/WebObjects/MZStore.woa/wpa/MRSS/newreleases/sf=143441/limit=25/rss.xml
我嘗試使用item標籤和元素itms:artist
來解析標題元素。
我不知道如何處理標籤名稱空間
其實我也問題與_namespaces_元素,u能告訴我如何處理它。還有一個如果像_title_這樣的元素是它的一部分,那麼標籤**項**和**通道**的一部分,那麼我怎樣才能控制只讀取標籤**項**的_title_元素 – jaya
[使用saxparser的命名空間]( http://stackoverflow.com/questions/7815526/how-to-parse-xml-with-namespace-using-android-sax-parser) – Harish