本帖最后由 冯盼 于 2012-12-4 23:20 编辑
主要处理程序:
public class XMLContentHandler extends DefaultHandler {
private static final String TAG = "xml";
private List<person> persons;
private person perso;
private String preTag;
public List<person> getpersons()
{
return persons;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if(perso!=null)
{
String data = new String(ch,start,length);
if("name".equals(preTag))
{
perso.setname(data);
}
else if("age".equals(preTag))
{
perso.setage(new Short(data));
}
}
Log.i(TAG, "正在解析出来的XML内容:"+new String(ch,start,length));
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
Log.i(TAG, "XML文档解析完毕了!");
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("person".equals(localName)&&perso!=null)
{
persons.add(perso);
perso=null;
}
preTag=null;
Log.i(TAG, localName+"XML文档解析完毕了!");
}
@Override
public void startDocument() throws SAXException {
persons = new ArrayList<person>();
Log.i(TAG, "startDocument开始解析XML文档!");
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if("person".equals(localName))
{
perso = new person();
perso.setid(new Integer(attributes.getValue("id")));
}
preTag=localName;
Log.i(TAG, "开始解析XML文档元素:"+localName);
}
}
主要处理程序的调用模块:
public class saxPersonService {
public static List<person> readXML(InputStream instream) throws Exception
{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLContentHandler xch = new XMLContentHandler();
sp.parse(instream, xch);
instream.close();
return xch.getpersons();
}
}
Main主程序:
public class SaxActivity extends Activity {
Button btnread = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnread = (Button)findViewById(R.id.btnRead);
btnread.setOnClickListener(listener);
}
OnClickListener listener = new OnClickListener()
{
@Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btnRead:
InputStream instream = null;
person pp = null;
try {
instream = SaxActivity.this.openFileInput("person.xml");
List<person> persons = saxPersonService.readXML(instream);
pp = persons.get(0);
Toast.makeText(SaxActivity.this, "读取成功!\n"+pp.getid()+"\n"+pp.getname()+"\n"+pp.getage(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Toast.makeText(SaxActivity.this, "读取成功!"+pp.getid()+"\n"+pp.getname()+"\n"+pp.getage(), Toast.LENGTH_LONG).show();
break;
}
}
};
} |
|