Person.java
package org.email;
public class Person {
private String name;
private String e_mail;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getE_mail() {
return e_mail;
}
public void setE_mail(String e_mail) {
this.e_mail = e_mail;
}
}
SaxReadXml.java
package org.email;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
public class SaxReadXml extends DefaultHandler {
private Person person;
private List<Person> personList;
private String oo;
public static final String RECORD = @H_365_502@"RECORD";
public static final String NAME = @H_365_502@"NAME";
public static final String E_MAIL = @H_365_502@"E_MAIL";
public List<Person> getPersonList() {
return personList;
}
public List<Person> readXml(InputStream in) throws Exception {
SaxReadXml srx = new SaxReadXml();
XMLReader xr = XMLReaderFactory
.createXMLReader("org.apache.xerces.parsers.SAXParser");
xr.setContentHandler(srx);
// xr.parse(new InputSource(new FileReader(""))); //乱码
xr.parse(new InputSource(in));
return srx.getPersonList();
}
public static void main(String[] args) {
SaxReadXml srx = new SaxReadXml();
try {
List<Person> list = srx.readXml(srx.getClass().getClassLoader()
.getResourceAsStream("ff.xml"));
for (Person p : list) {
System.out.println(p.getName() + ":" + p.getE_mail());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void startDocument() throws SAXException {
personList = new ArrayList<Person>();
}
@Override
public void characters(char[] ch,int start,int length)
throws SAXException {
String data = new String(ch,start,length);
if (E_MAIL.equals(oo)) {
person.setE_mail(data);
}
if (NAME.equals(oo)) {
person.setName(data);
}
}
@Override
public void startElement(String uri,String localName,String name,
Attributes attributes) throws SAXException {
if (RECORD.equals(localName)) {
person = new Person();
// person.setId(new Integer(attributes.getValue("ID")));
}
oo = localName;
}
@Override
public void endElement(String uri,String name)
throws SAXException {
if (RECORD.equals(localName) && person != null) {
personList.add(person);
person = null;
}
oo = null;
}
}
ff.xml
<?xml version="1.0" encoding="UTF-8"?>
<RECORDS>
<RECORD>
<NAME>XXX</NAME>
<E_MAIL>6364644915@qq.com</E_MAIL>
</RECORD>
<RECORD>
<NAME>BBBBB</NAME>
<E_MAIL>754545408010@qq.com</E_MAIL>
</RECORD>
</RECORDS>