SAX解析XML例子

    xiaoxiao2021-12-15  27

    Demo类:

    import java.util.Iterator; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class SAXDemo { public static void main(String[] args) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); MyHandler handler = new MyHandler(); parser.parse("D:/bookstore.xml", handler); List<Book> books = handler.getInfo(); Iterator<Book> iterator = books.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

    Handler类:

    import java.util.ArrayList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class MyHandler extends DefaultHandler { private Book book; private List<Book> books = new ArrayList<Book>(); private String tag; public List<Book> getInfo() { return books; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub tag = qName; if ("book".equals(qName)) { book = new Book(); } if ("title".equals(qName)) { book.setLangguage(attributes.getValue("lang")); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub String newString = new String(ch, start, length); if ("title".equals(tag)) { book.setTitle(newString); } else if ("author".equals(tag)) { book.setAuthor(newString); } else if ("year".equals(tag)) { book.setYear(Integer.parseInt(newString)); } else if ("price".equals(tag)) { book.setPrice(Double.parseDouble(newString)); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub tag = ""; if ("book".equals(qName)) { books.add(book); } } }

    基本类:

    public class Book { private String title; private String author; private int year; private double price; private String langguage; public Book() { // TODO Auto-generated constructor stub } public String getLangguage() { return langguage; } public void setLangguage(String langguage) { this.langguage = langguage; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "title=" + title + ", author=" + author + ", year=" + year + ", price=" + price + ", langguage=" + langguage; } }
    转载请注明原文地址: https://ju.6miu.com/read-1000169.html

    最新回复(0)