sax解析案例(javabean封装xml文档数据)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package itcast.sax; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import javax.xml.parsers.ParserConfigurationException; 7 import javax.xml.parsers.SAXParser; 8 import javax.xml.parsers.SAXParserFactory; 9 10 import org.xml.sax.SAXException; 11 import org.xml.sax.XMLReader; 12 13 public class Demo { 14 15 @SuppressWarnings("unchecked") 16 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { 17 //1、创建解析工程 18 SAXParserFactory factory = SAXParserFactory.newInstance(); 19 20 //2、得到解析器 21 SAXParser sp = factory.newSAXParser(); 22 23 //3、得到读取器 24 XMLReader reader = sp.getXMLReader(); 25 26 //4、设置内容处理器 27 BeanListHandler handler = new BeanListHandler(); 28 reader.setContentHandler(handler); 29 30 //5、读取xml文档内容 31 reader.parse("src/book.xml"); 32 33 34 List<Book> list = handler.getList(); 35 System.out.println(list); 36 } 37 38 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package itcast.sax; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.xml.sax.Attributes; 7 import org.xml.sax.SAXException; 8 import org.xml.sax.helpers.DefaultHandler; 9 10 //把xml文档中的每一本封装到一个book对象,并把多个book对象放在一个list集合中 11 public class BeanListHandler extends DefaultHandler { 12 13 private List list = new ArrayList(); 14 private String currentTag; 15 private Book book; 16 17 @Override 18 public void characters(char[] ch, int start, int length) 19 throws SAXException { 20 if("bookname".equals(currentTag)){ 21 String bookname = new String(ch,start,length); 22 book.setName(bookname); 23 } 24 if("editor".equals(currentTag)){ 25 String author = new String(ch,start,length); 26 book.setAuthor(author); 27 } 28 if("price".equals(currentTag)){ 29 String price = new String(ch,start,length); 30 book.setPrice(price); 31 } 32 } 33 34 @Override 35 public void endElement(String uri, String localName, String name) 36 throws SAXException { 37 if(name.equals("书")){ 38 list.add(book); 39 book=null; 40 } 41 currentTag = null; 42 } 43 44 @Override 45 public void startElement(String uri, String localName, String name, 46 Attributes attributes) throws SAXException { 47 48 currentTag=name; 49 if("书".equals(currentTag)){ 50 book = new Book(); 51 } 52 53 } 54 55 public List getList() { 56 return list; 57 } 58 59 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <书架> 3 <书> 4 <bookname name="zero">java jiuyepeixunjiaocheng</bookname> 5 <editor>zhangxiaoxiang</editor> 6 <price>109yuan</price> 7 </书> 8 <书> 9 <bookname>javaWebprogramming</bookname> 10 <editor>lihuoming</editor> 11 <price>28.00yuan</price> 12 </书> 13 </书架>