前端之家收集整理的这篇文章主要介绍了
JaxpSax解析XML,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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 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,length));
}
if("售价".equals(currentElementName)){
book.setPrice(new String(ch,length));
}
}
}