XML解析SAX

前端之家收集整理的这篇文章主要介绍了XML解析SAX前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public class SaxXML extends DefaultHandler {

    private List<Book> bookList;
    private Book book;
    private String tagName;

    public void startDocument(){
        bookList = new ArrayList<Book>();
        System.out.println("开始读文挡了");
    }



    @Override
    public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
        System.out.println("开始读元素了");
        if("Book".equals(qName)){
            book = new Book();
            book.setId(Integer.parseInt(attributes.getValue("id")));
        }
        tagName = qName;

    }

    @Override
    public void characters(char[] ch,int start,int length)
            throws SAXException {
        System.out.println("文本解析中");
        if(book !=null){
            String content = new String(ch,start,length);
            if(tagName.equals("bookName")){
                book.setBookName(content);
            }else if(tagName.equals("bookAuthor")){
                book.setBookAuthor(content);
            }if(tagName.equals("bookISBN")){
                book.setBookISBN(content);
            }else if(tagName.equals("bookPrice")){
                book.setBookPrice(Double.parseDouble(content));
            }

        }
    }



    @Override
    public void endElement(String uri,String qName)
            throws SAXException {
        System.out.println("元素结束了");
        if(qName.equals("Book")){
            bookList.add(book);
            book=null;
        }
        tagName="";
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("文档结束了");
    }



    public List<Book> getBookList() {

        return bookList;
    }


}
原文链接:https://www.f2er.com/xml/294851.html

猜你在找的XML相关文章