package com.xiva.service;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.xiva.domain.Person;
public class XmlContentHandler extends DefaultHandler{
private List<Person> personList;
private Person person;
private String perTag;
public List<Person> getPersonList() {
return personList;
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
personList = new ArrayList<Person>();
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(person!=null){
String data = new String(ch,start,length);
if("name".equals(perTag))
{
person.setPersonName(data);
}else if("age".equals(perTag))
{
person.setAge(data);
}
}
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if("person".equals(localName))
{
person = new Person();
person.setId(new Integer(attributes.getValue("id")));
}
perTag = localName;
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("person".equals(localName) && person!=null){
personList.add(person);
person = null;
}
perTag = null;
}
}
package com.xiva.xml;
import java.io.InputStream; import java.util.List; import com.xiva.domain.Person; import com.xiva.service.SAXService; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; public class XMLActivity extends Activity { /** Called when the activity is first created. */ private static final String TAG = "XMLActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView text = (TextView)this.findViewById(R.id.content); InputStream iStream = XMLActivity.class.getClassLoader().getResourceAsStream("person.xml"); List<Person> personList; try { personList = SAXService.readXML(iStream); StringBuffer strB = new StringBuffer(); for(Person person:personList) { String str = person.toString(); strB.append(str); } text.setText(strB); } catch(Exception e){ Log.i(TAG, "Xml Load failure!"); Toast.makeText(XMLActivity.this, "Xml Load failure!", 1).show(); e.printStackTrace(); } } }
完整代码见附件。