现代的JDK提供了一种更现代的流解析方式,这种方式更加简单,避免了使用回调事件。回调事件是一种被动的等待,必须在特定的方法中进行处理。现代的流机制称为"拉取流机制",它可以让程序自己决定去拉取信息。其实就是把SAX的分开的事件可以写在一个方法中。
例:
现F盘有book.xml文件:
<?xml version="1.0" encoding="GB2312"?>
<bookstore>
<book category="COOKING">
<title lang="en">西游记</title>
<author>吴承恩</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="COOKING">
<title lang="en">水浒传</title>
<author>施耐庵</author>
<year>2003</year>
<price>29.00</price>
</book>
</bookstore>
实体类:
package com.modernsax.entity;
import java.io.Serializable;
public class BookInfo implements Serializable{
private String title;
private String author;
private String year;
private String price;
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 String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
操作类:
package com.modernsax.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import com.modernsax.entity.BookInfo;
public class BookInfoStaxDemo {
public static void main(String[] args) {
/*String path = FileReader.class.getResource("/").getFile();
String xmlName = path + "/bookstore.xml";*/
String fileName="F:"+File.separator+"book.xml";
List<BookInfo> bookList = readerBookInfo(fileName);
for (BookInfo book : bookList) {
System.out.println(book.getTitle() + ";" + book.getAuthor());
}
}
private static List<BookInfo> readerBookInfo(String xmlName) throws FactoryConfigurationError {
List<BookInfo> bookList = new ArrayList<BookInfo>();
try {
XMLInputFactory xif = XMLInputFactory.newFactory();
InputStream input = new FileInputStream(xmlName);
XMLStreamReader xmlReader = xif.createXMLStreamReader(input);
BookInfo book = null;
String preTag = "";
while (xmlReader.hasNext()) {
int event = xmlReader.next();
if (event == XMLStreamReader.START_ELEMENT) {
preTag = xmlReader.getLocalName();
if (preTag.equals("book")) {
book = new BookInfo();
}
} else if (event == XMLStreamReader.END_ELEMENT) {
if (xmlReader.getLocalName().equals("book")) {
bookList.add(book);
}
preTag = "";
} else if (event == XMLStreamReader.CHARACTERS) {
String context = xmlReader.getText();
if (preTag.equals("title")) {
book.setTitle(context);
} else if (preTag.equals("author")) {
book.setAuthor(context);
} else if (preTag.equals("year")) {
book.setYear(context);
} else if (preTag.equals("price")) {
book.setPrice(context);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bookList;
}
}
控制台输出如下:
西游记;吴承恩
水浒传;施耐庵