import java.io.*;
public class Book implements Serializable {
private int id;
private String name;
private double price;
public Book(){}
public Book(int id,String name,double price){
this.id=id;
this.name=name;
this.price=price;
}
public void setId(int id){
this.id=id;
}
public void setName(String name){
this.name=name;
}
public void setPrice(double price){
this.price=price;
}
}
当然主要看这里:
public class SaxParseService extends DefaultHandler {
private List bookList;
private Book book;
private Stack stack=new Stack();
public List getBooks(InputStream inputStream,
SaxParseService saxParseService)
throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(inputStream, saxParseService);
return saxParseService.getBooks();
}
public List getBooks() {
return this.bookList;
}
@Override
public void startDocument() throws SAXException {
//***原样输出xml
System.out.println("");
//***原样输出xml
bookList = new ArrayList();
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
//***原样输出xml
System.out.print("<"+qName);
if(attributes!=null&&attributes.getLength()>0){
for(int i=0;i
String attrName=attributes.getQName(i);
String attrValue=attributes.getValue(i);
System.out.print(" "+attrName+"="+"\""+attrValue+"\"");
}
}
System.out.print(">");
//***原样输出xml
if ("book".equals(qName)) {
book = new Book();
book.setId(Integer.valueOf(attributes.getValue(0)));
}
stack.push(qName);
//System.out.println("startElement:"+stack.size());
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//***原样输出xml
System.out.print("");
//***原样输出xml
if ("book".equals(qName)) {
bookList.add(book);
book = null;
}
stack.pop();
//System.out.println("endElement:"+stack.size());
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
//***原样输出xml
System.out.print(new String(ch,start,length));
//***原样输出xml
String preTagName=stack.peek();
//System.out.println("characters:"+stack.size());
if (preTagName != null) {
String content = new String(ch, start, length);
if ("name".equals(preTagName)) {
book.setName(content);
} else if ("price".equals(preTagName)) {
book.setPrice(Double.valueOf(content));
}
}
}
}