1.准备工作
public class Book {
private int id;
private String name;
private float price;
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "书号:"+this.id+" 书名:"+this.name+" 售价:"+this.price;
}
}
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MySAXParseService extends DefaultHandler {
private Book book = null;
private List<Book> bookList = null;
private String preTag = null;
public void startDocument() throws SAXException {
bookList = new ArrayList<Book>();
super.startDocument();
}
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if(name.equals("book"))
{
book = new Book();
book.setId(Integer.parseInt(attributes.getValue(0)));
}
preTag = name;
super.startElement(uri, localName, name, attributes);
}
public void endElement(String uri, String localName, String name)
throws SAXException {
if(name.equals("book"))
{
bookList.add(book);
book = null;
}
preTag = null;
super.endElement(uri, localName, name);
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if(preTag!=null)
{
String content = new String(ch,start,length);
if("name".equals(preTag))
{
book.setName(content);
}
else if("price".equals(preTag))
{
book.setPrice(Float.parseFloat(content));
}
}
super.characters(ch, start, length);
}
public List<Book> getBooks() {
return bookList;
}
}
2.开始解析
import java.io.File;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.hust.utils.Book;
import com.hust.utils.MySAXParseService;
public class SAXParse {
/**
* @param args
*/
//public static List<Book> result = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
MySAXParseService service = new MySAXParseService();
sp.parse(new File("books.xml"), service);
List<Book> books = service.getBooks();
for(Book book:books)
{
System.out.println(book.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
}
}