SAX加深案例

    SAX加深案例,进一步通过案例解说SAX的用法,本次案例包括解说怎么获取xml文件中的各种子节点,详细介绍情况下例:

主要类:Demo5.java

package com.sax;

import java.io.IOException;
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 Demo5 {

 /**
  * @param args
  * @throws SAXException
  * @throws ParserConfigurationException
  * @throws IOException
  */
 public static void main(String[] args) throws ParserConfigurationException,
   SAXException, IOException {

  SAXParserFactory spf = SAXParserFactory.newInstance();
  SAXParser sp = spf.newSAXParser();
  XMLReader reader = sp.getXMLReader();
  BookHandler bh = new BookHandler();
  reader.setContentHandler(bh);
  reader.parse("src/book.xml");
  List<Book> list = bh.getBook();
  for(Book book:list){
   System.out.println(book.getName()+"---"+book.getAuthor()+"---"+book.getPrice());
  }
 }

}

class BookHandler extends DefaultHandler {
 private List<Book> list = new ArrayList<Book>();
 private String currentName;
 private Book book;

 @Override
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {
  currentName = qName;
  if ("book".equals(currentName)) {
   book = new Book();
  }
 }

 public List<Book> getBook() {
  return list;
 }

 public void characters(char[] ch, int start, int length)
   throws SAXException {
  if ("bookname".equals(currentName)) {
   String value = new String(ch,start,length);
   book.setName(value);
  }
  if ("author".equals(currentName)) {
   String value = new String(ch,start,length);
   book.setAuthor(value);
  }
  if ("price".equals(currentName)) {
   String value = new String(ch,start,length);
   book.setPrice(value);
  }

 }

 @Override
 public void endElement(String uri, String localName, String qName)
   throws SAXException {
  if("book".equals(qName)){
   list.add(book);
   book = null;
  }
  currentName = null;
 }
}

 java bean :book.java

package com.sax;

public class Book {

 private String name;
 private String author;
 private String price;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAuthor() {
  return author;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 public String getPrice() {
  return price;
 }
 public void setPrice(String price) {
  this.price = price;
 }
}

 

posted @ 2012-10-12 19:07  yangkai_keven  阅读(119)  评论(0编辑  收藏  举报