- package com.imooc_xml.sax.handler;
- import java.util.ArrayList;
- import org.xml.sax.Attributes;
- import org.xml.sax.SAXException;
- import org.xml.sax.helpers.DefaultHandler;
- import com.imooc_xml.sax.entity.Book;
- public classSAXParserHandlerextends DefaultHandler {
- //使用全局变量可以使本类的各个方法通用,联系
- intbookIndex = 0 ;
- String value =null;
- Book book =null;
- privateArrayList bookList = newArrayList();
- publicArrayList getBookList() {
- return bookList;
- }
- /**
- * 用来遍历xml文件的开始标签
- */
- @Override
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) throws SAXException {
- // TODO Auto-generated method stub
- super.startElement(uri, localName, qName, attributes);
- ////解析xml文件的节点属性,只有book节点有属性
- if(qName.equals("book")){
- book =new Book();
- bookIndex++;
- //已知book的属性名
- // attributes.getValue("id");
- //不知book元素的属性名和个数
- intnum = attributes.getLength();
- for(inti=0;i){
- //book元素的第i+1个属性名
- attributes.getQName(i);
- attributes.getValue(i);
- if(attributes.getQName(i).equals("id")){
- book.setId(attributes.getValue(i));
- }
- }
- }else if(!qName.equals("book")&&!qName.equals("bookstore")){
- //节点名
- System.out.println(qName);
- }
- }
- /**
- * 用来遍历xml文件的结束标签
- */
- @Override
- public void endElement(String uri, String localName, String qName)
- throws SAXException {
- // TODO Auto-generated method stub
- super.endElement(uri, localName, qName);
- //判断是否针对一本书已经遍历结束
- if(qName.equals("book")){
- bookList.add(book);
- book =null;
- System.out.println("结束遍历第"+bookIndex+"本书");
- }else if(qName.equals("name")){
- book.setName(value);
- }else if(qName.equals("author")){
- book.setAuthor(value);
- }else if(qName.equals("year")){
- book.setYear(value);
- }else if(qName.equals("price")){
- book.setPrice(value);
- }else if(qName.equals("language")){
- book.setLanguage(value);
- }
- }
- @Override
- public voidcharacters(char[] ch,intstart,int length)
- throws SAXException {
- // TODO Auto-generated method stub
- super.characters(ch, start, length);
- //ch是节点之间的文本内容value =new String(ch, start, length);
- //判断空格和换行
- if(!value.trim().equals("")){
- System.out.println(value);
- }
- }
- /**
- * 用来标志解析开始
- */
- @Override
- public voidstartDocument()throws SAXException {
- // TODO Auto-generated method stub
- super.startDocument();
- System.out.println("SAX解析开始");
- }
- /**
- * 用来标志解析结束
- */
- @Override
- public voidendDocument()throws SAXException {
- // TODO Auto-generated method stub
- super.endDocument();
- System.out.println("SAX解析结束");
- }
- }
来源: http://www.bubuko.com/infodetail-1949181.html