<?xml version="1.0" encoding="UTF-8"?> <书架> <书> <书名>书名1</书名> <作者>作者1</作者> <售价>售价1</售价> </书> <书> <书名>书名2</书名> <作者>作者2</作者> <售价>售价2</售价> </书> </书架>
创建Book类来封装解析出来的xml
package day04; public class Book { private String name; private String author; private String price; public String getName() { return name; } public Book() { } public Book(String name, String author, String price) { this.name = name; this.author = author; this.price = price; } 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; } }
sax--解析过程
package day04; 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 Demo3 { //sax解析xml文档 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException{ Demo3 d=new Demo3(); //1.创建解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //2.得到解析器 SAXParser sp=factory.newSAXParser(); //3.得到读取器 XMLReader reader=sp.getXMLReader(); //4.设置内容处理器 BeanListHander Hander=d.new BeanListHander(); reader.setContentHandler(Hander); //5.读取xml文档内容 reader.parse("src/Book.xml"); List<Book> list=Hander.getBooks(); System.out.println(list ); } //把xml文档中每一本书封装到一个book对象,并把多个对象放到一个list集合中返回 class BeanListHander extends DefaultHandler{ private List<Book> list=new ArrayList<Book>();//存入list集合中 private String currentTag;//记住当前解析到的是什么标签 private Book book; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { currentTag=qName; if("书".equals(currentTag)){ book=new Book(); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if("书名".equals(currentTag)){ String name = new String(ch,start,length); book.setName(name); } if("作者".equals(currentTag)){ String author= new String(ch,start,length); book.setAuthor(author); } if("售价".equals(currentTag)){ String price = new String(ch,start,length); book.setPrice(price); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equals("书")){ list.add(book); book=null; } currentTag=null; } public List<Book> getBooks() { return list; } } }
节点打到这一句:
List<Book> list=Hander.getBooks();
时间: 2024-10-27 19:53:31