JaxpSax解析XML

来源:互联网 发布:python调用linux命令 编辑:程序博客网 时间:2024/06/16 08:16

import java.util.ArrayList;import java.util.List;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;import Book;//要把数据封装到对象中public class SAXDemo3 {public static void main(String[] args) throws Exception {SAXParser parser = SAXParserFactory.newInstance().newSAXParser();XMLReader reader = parser.getXMLReader();List<Book> books = new ArrayList<Book>();reader.setContentHandler(new MyContentHandler2(books));reader.parse("src/book.xml");//验证for(Book b:books)System.out.println(b);}}class MyContentHandler2 extends DefaultHandler{private List<Book> books;public MyContentHandler2(List<Book> books){this.books = books;}private Book book;private String currentElementName;public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {currentElementName = qName;if("书".equals(qName)){book = new Book();}}public void endElement(String uri, String localName, String qName)throws SAXException {if("书".equals(qName)){books.add(book);book = null;}currentElementName = null;}public void characters(char[] ch, int start, int length)throws SAXException {if("书名".equals(currentElementName)){book.setName(new String(ch,start,length));}if("作者".equals(currentElementName)){book.setAuthor(new String(ch,start,length));}if("售价".equals(currentElementName)){book.setPrice(new String(ch,start,length));}}}


0 0
原创粉丝点击