試試我的代碼是從資產/ URL
public class SaxParserTest extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
ArrayList<HashMap<String, Object>> datalist = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> temp;
public ArrayList<HashMap<String, Object>> getData(Context context){
try {
SAXParserFactory saxparser = SAXParserFactory.newInstance();
SAXParser parser = saxparser.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(SaxParserTest.this);
/*
* used when pick local data
*/
// InputStream is =context.getAssets().open("data.xml");
// xmlReader.parse(new InputSource(is));
/*
* used when pick data from url
*/
URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml");
xmlReader.parse(new InputSource(url.openStream()));
} catch (Exception e) {
e.getMessage();
}
return datalist;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("CD")) {
temp=new HashMap<String, Object>();
temp.put(Constant.id, attributes.getValue(Constant.id));
// temp.put(Constant.title, attributes.getValue(Constant.title));
// temp.put(Constant.artist, attributes.getValue(Constant.artist));
// temp.put(Constant.country, attributes.getValue(Constant.country));
// temp.put(Constant.company, attributes.getValue(Constant.company));
// temp.put(Constant.price, attributes.getValue(Constant.price));
// temp.put(Constant.year, attributes.getValue(Constant.year));
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
currentValue = new String(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(localName.equals(Constant.title))
temp.put(Constant.title, currentValue);
if(localName.equals(Constant.artist))
temp.put(Constant.artist, currentValue);
if(localName.equals(Constant.country))
temp.put(Constant.country, currentValue);
if(localName.equals(Constant.company))
temp.put(Constant.company, currentValue);
if(localName.equals(Constant.price))
temp.put(Constant.price, currentValue);
if(localName.equals(Constant.year))
temp.put(Constant.year, currentValue);
if(localName.equalsIgnoreCase("CD"))
datalist.add(temp);
Log.i("DataList", datalist.toString());
}
}
分析數據,並使用該像
SaxParserTest test=new SaxParserTest();
datal=test.getData(this);
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, datal,
R.layout.activity_main, new String[] { Constant.title,
Constant.artist, Constant.price, Constant.year,
Constant.company, Constant.country ,Constant.id}, new int[] {
R.id.txt1, R.id.txt2, R.id.txt3, R.id.txt4,
R.id.txt5, R.id.txt6 ,R.id.txt7});
setListAdapter(adapter);
ü也可以使用Maven庫序列化和Android的反序列化XML它很容易 –