public class MainActivity extends Activity implements OnClickListener {
private List<Person> list;
private Button jx;
private ContentHandler handler =
new DefaultHandler() {
private String targetName;
private Person p;
@Override
public void startDocument()
throws SAXException {
System.out.println(
"开始读取文件");
list =
new ArrayList<Person>();
super.startDocument();
}
@Override
public void endDocument()
throws SAXException {
System.out.println(
"文件读取完毕");
super.endDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes)
throws SAXException {
targetName = localName;
System.out.println(
"++++++++" + targetName);
if (
"student".equals(targetName)) {
p =
new Person();
String id = attributes.getValue(
"id");
p.setId(Integer.parseInt(id));
}
super.startElement(uri, localName, qName, attributes);
}
@Override
public void characters(
char[] ch,
int start,
int length)
throws SAXException {
if (targetName !=
null) {
String text =
new String(ch, start, length);
System.out.println(
"text+++++++" + text);
if (
"name".equals(targetName)) {
p.setName(text);
}
else if (
"age".equals(targetName)) {
p.setAge(Integer.parseInt(text));
}
}
super.characters(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.println(
"结束标签"+localName);
if (
"student".equals(localName)) {
list.add(p);
p =
null;
}
targetName =
null;
super.endElement(uri, localName, qName);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jx = (Button) findViewById(R.id.jx);
jx.setOnClickListener(
this);
}
@Override
public void onClick(View v) {
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser saxParser = spf.newSAXParser();
XMLReader reader = saxParser.getXMLReader();
reader.setContentHandler(handler);
reader.parse(
new InputSource(getAssets().open(
"data1.xml")));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
javabean
public class Person {
private int id;
private String name;
private int age;
public Person() {
super();
}
public Person(
int id, String name,
int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(
int id) {
this.id = id;
}
public String
getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(
int age) {
this.age = age;
}
@Override
public String
toString() {
return "Person [id=" + id +
", name=" + name +
", age=" + age +
"]";
}
}
转载请注明原文地址: https://ju.6miu.com/read-1125716.html