本帖最后由 狂飙的yellow.co 于 2013-6-7 16:52 编辑
其中将获取的对象取出,却悲剧了,结果是空.....,求解- package XMLDay;
- import java.util.ArrayList;
- import java.util.Iterator;
- 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 Demo6 {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- //获取工厂类
- SAXParserFactory factory = SAXParserFactory.newInstance();
-
- //获取解析器
- SAXParser sp = factory.newSAXParser();
-
- //获取XML读取器
- XMLReader reader = sp.getXMLReader();
-
-
- //确定数据的handler 处理类
- BeanListHandle handle = new BeanListHandle();
- reader.setContentHandler(handle);
-
- //读取数据
- reader.parse("src/book.xml");
-
- //获取读取的XML数据
- ArrayList<Book> list = handle.getBooks();
- // 通过Iterator 迭代的方法,去除数据,我这儿有问题了
- // Iterator<Book> it = list.iterator();
- //
- // while(it.hasNext()){
- // Book book = it.next(); // 获取Book对象
- // String name = book.getName();
- // String author = book.getAuthor();
- // String price = book.getPrice();
- // System.out.println(name+"__"+author+"__"+price);
- // }
- }
- }
- //将获取的类变成对象
- class BeanListHandle extends DefaultHandler{
- private String currentName;
- private ArrayList<Book> list = new ArrayList<Book>();
- private Book book;
- @Override
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) throws SAXException {
- currentName = qName;
- if("书".equals(currentName)){
- this.book = new Book();
- }
- }
- @Override
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- if("书名".equals(currentName)){
- String name = new String(ch,start,length);
- book.setName(name);
- }
- if("作者".equals(currentName)){
- String author = new String(ch,start,length);
- book.setAuthor(author);
- }
- if("价格".equals(currentName)){
- String prise = new String(ch,start,length);
- book.setPrice(prise);
- }
- }
- @Override
- public void endElement(String uri, String localName, String qName)
- throws SAXException {
- //将定义的标签给删掉
- if(qName.equals("书")){
- list.add(book);
- book = null; //将Book数据初始化
- }
- currentName = null;//将当前的数据初始化
- }
- //获取List集合
- //获取数据的Book数据
- public ArrayList<Book> getBooks() {
- return list;
- }
-
-
- }
复制代码 |
|