SAX是Simple API for XML的缩写,它并不是由W3C官方所提出的标准,虽然如此,使用SAX的还是不少,几乎所有的XML解析器都会支持它。
与DOM比较而言,SAX是一种轻量型的方法。我们知道,在处理DOM的时候,我们需要读入整个的XML文档,然后在内存中创建DOM树,生成DOM树上的每个Node对象。当文档比较小的时候,这不会造成什么问题,但是一旦文档大起来,处理DOM就会变得相当费时费力。特别是其对于内存的需求,也将是成倍的增长,以至于在某些应用中使用DOM是一件很不划算的事(比如在applet中)。这时候,一个较好的替代解决方法就是SAX。
SAX在概念上与DOM完全不同。它不同于DOM的文档驱动,它是事件驱动的,它并不需要读入整个文档,而文档的读入过程也就是SAX的解析过程。所谓事件驱动,是指一种基于回调(callback)机制的程序运行方法。
下面对这个xml文件使用sax解析:
<?xml version="1.0" encoding="UTF-8"?> <node> <book> <title>JAVA编程思想</title> <author>XX</author> <price>12.5</price> </book> <book> <title>Effective Java</title> <author>Jack</author> <price>22.5</price> <批发价>18</批发价> </book> <book> <title>Lenove</title> <brand>郑州</brand> <price>3999</price> </book> </node>
xml对应的Javabean:
public class Book { private String bookName; private String author; private double price; public Book() { } public Book(String bookName, String author, double price) { this.bookName = bookName; this.author = author; this.price = price; } @Override public String toString() { return "Book [bookName=" + bookName + ", author=" + author + ", price=" + price + "]"; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
开始解析:
import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; public class SaxTest2 { /** * @param args * @throws Exception * @throws ParserConfigurationException */ public static void main(String[] args) throws Exception { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); XMLReader reader = parser.getXMLReader(); final List<Book> books = new ArrayList<Book>(); reader.setContentHandler(new DefaultHandler(){ Book book = null; String node = null; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if("book".equals(qName)) { book = new Book(); } node = qName; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("book".equals(qName)) { books.add(book); book = null; } node = null; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if("title".equals(node)) { book.setBookName(new String(ch,start,length)); } if("author".equals(node)) { book.setAuthor(new String(ch,start,length)); } if("price".equals(node)) { book.setPrice(Double.parseDouble(new String(ch,start,length))); } }}); reader.parse("src/demo.xml"); for(Book b : books) { System.out.println(b); } } }