您可以创建一个扩展 DefaultHandler 的自定义处理程序,并使用它来解析您的 XML 并为您生成 List<Book>。
处理程序将维护一个List<Book> 并且:
- 每次遇到书的开始标签,都会创建一个新的
Book
- 每次遇到书的end标签时,都会将这个
Book添加到列表中。
最后它将保存完整的图书列表,您可以通过其getBooks() 方法访问它
假设这本书类:
class Book {
private String category;
private String title;
private String author;
private String year;
private String price;
// GETTERS/SETTERS
}
您可以像这样创建自定义处理程序:
class MyHandler extends DefaultHandler {
private boolean title = false;
private boolean author = false;
private boolean year = false;
private boolean price = false;
// Holds the list of Books
private List<Book> books = new ArrayList<>();
// Holds the Book we are currently parsing
private Book book;
public void startElement(String uri, String localName,String qName, Attributes attributes) {
switch (qName) {
// Create a new Book when finding the start book tag
case "book": {
book = new Book();
book.setCategory(attributes.getValue("category"));
}
case "title": title = true;
case "author": author = true;
case "year": year = true;
case "price": price = true;
}
}
public void endElement(String uri, String localName, String qName) {
// Add the current Book to the list when finding the end book tag
if("book".equals(qName)) {
books.add(book);
}
}
public void characters(char[] ch, int start, int length) {
String value = new String(ch, start, length);
if (title) {
book.setTitle(value);
title = false;
} else if (author) {
book.setAuthor(value);
author = false;
} else if (year) {
book.setYear(value);
year = false;
} else if (price) {
book.setPrice(value);
price = false;
}
}
public List<Book> getBooks() {
return books;
}
}
然后您使用此自定义处理程序进行解析并检索书籍列表
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
MyHandler myHandler = new MyHandler();
saxParser.parse("/path/to/file.xml", myHandler);
List<Book> books = myHandler.getBooks();