books.xml
冰与火之歌
乔治马丁
2014
89
安徒生童话
安徒生
2004
77
think think think
aaa
1997
100
bean类:Book.java
public class Book {
/**
* @author lune
*/
private int id;
private String name;
private String author;
private int year;
private double price;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the author
*/
public String getAuthor() {
return author;
}
/**
* @param author the author to set
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* @return the year
*/
public int getYear() {
return year;
}
/**
* @param year the year to set
*/
public void setYear(int year) {
this.year = year;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author + ", year=" + year + ", price=" + price + "]";
}
}
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import com.lune.bean.Book;
/**
* 用DOM方式读取xml文件
* @author lune
*/
public class ReadxmlByDom {
private static DocumentBuilderFactory dbFactory = null;
private static DocumentBuilder db = null;
private static Document document = null;
private static List books = null;
static{
try {
dbFactory = DocumentBuilderFactory.newInstance();
db = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
public static List getBooks(String fileName) throws Exception{
//将给定 URI 的内容解析为一个 XML 文档,并返回Document对象
document = db.parse(fileName);
//按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
NodeList bookList = document.getElementsByTagName("book");
books = new ArrayList();
//遍历books
for(int i=0;i contents = new ArrayList<>();
for(int j=1;j list = ReadxmlByDom.getBooks(fileName);
for(Book book :list){
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.lune.bean.Book;
/**
* 用SAX解析xml文件时需要的handler
* @author lune
*/
public class SAXParseHandler extends DefaultHandler {
private List list; //存放解析到的book数组
private Book book; //存放当前解析的book
private String content = null; //存放当前节点值
/**
* 开始解析xml文档时调用此方法
*/
@Override
public void startDocument() throws SAXException {
super.startDocument();
System.out.println("开始解析xml文件");
list = new ArrayList();
}
/**
* 文档解析完成后调用此方法
*/
@Override
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("xml文件解析完毕");
}
/**
* 开始解析节点时调用此方法
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
//当节点名为book时,获取book的属性id
if(qName.equals("book")){
book = new Book();
String id = attributes.getValue("id");//System.out.println("id值为"+id);
book.setId(Integer.parseInt(id));
}
}
/**
*节点解析完毕时调用此方法
*
*@param qName 节点名
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if(qName.equals("name")){
book.setName(content);
//System.out.println("书名"+content);
}else if(qName.equals("author")){
book.setAuthor(content);
// System.out.println("作者"+content);
}else if(qName.equals("year")){
book.setYear(Integer.parseInt(content));
// System.out.println("年份"+content);
}else if(qName.equals("price")){
book.setPrice(Double.parseDouble(content));
// System.out.println("价格"+content);
}else if(qName.equals("book")){ //当结束当前book解析时,将该book添加到数组后置为空,方便下一次book赋值
list.add(book);
book = null;
}
}
/**
* 此方法用来获取节点的值
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
content = new String(ch, start, length);
//收集不为空白的节点值
// if(!content.trim().equals("")){
// System.out.println("节点值为:"+content);
// }
}
public List getBooks(){
return list;
}
}
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.ParserFactory;
import com.lune.bean.Book;
import com.lune.handler.SAXParseHandler;
/**
* 用SAX方式读取xml文件
* @author lune
*/
public class ReadXmlBySAX {
private static List books = null;
private SAXParserFactory sParserFactory = null;
private SAXParser parser = null;
public List getBooks(String fileName) throws Exception{
SAXParserFactory sParserFactory = SAXParserFactory.newInstance();
SAXParser parser = sParserFactory.newSAXParser();
SAXParseHandler handler = new SAXParseHandler();
parser.parse(fileName, handler);
return handler.getBooks();
}
/**
* @param args
*/
public static void main(String[] args) {
try {
books = new ReadXmlBySAX().getBooks("src/res/books.xml");
for(Book book:books){
System.out.println(book);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.JDOM方式解析XML
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import com.lune.bean.Book;
import org.jdom2.*;
/**
* 用JDOM方式读取xml文件
* @author lune
*/
public class ReadXMLByJDom {
private List books = null;
private Book book = null;
public List getBooks(String fileName){
SAXBuilder saxBuilder = new SAXBuilder();
try {
Document document = saxBuilder.build(new FileInputStream(fileName));
//获取根节点bookstore
Element rootElement = document.getRootElement();
//获取根节点的子节点,返回子节点的数组
List bookList = rootElement.getChildren();
books = new ArrayList();
for(Element bookElement : bookList){
book = new Book();
//获取bookElement的属性
List bookAttributes = bookElement.getAttributes();
for(Attribute attribute : bookAttributes){
if(attribute.getName().equals("id")){
String id = attribute.getValue(); //System.out.println(id);
book.setId(Integer.parseInt(id));
}
}
//获取bookElement的子节点
List children = bookElement.getChildren();
for(Element child : children){
if(child.getName().equals("name")){
String name = child.getValue();//System.out.println(name);
book.setName(name);
}else if(child.getName().equals("author")){
String author = child.getValue();
book.setAuthor(author);//System.out.println(author);
}else if(child.getName().equals("year")){
String year = child.getValue();
book.setYear(Integer.parseInt(year));
}else if(child.getName().equals("price")){
String price = child.getValue();
book.setPrice(Double.parseDouble(price));
}
}
books.add(book);
book = null;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return books;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName = "src/res/books.xml";
List books= new ReadXMLByJDom().getBooks(fileName);
for(Book book : books){
System.out.println(book);
}
}
}
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.lune.bean.Book;
/**
* 用DOM4J方法读取xml文件
* @author lune
*/
public class ReadXMLByDom4j {
private List bookList = null;
private Book book = null;
public List getBooks(File file){
SAXReader reader = new SAXReader();
try {
Document document = reader.read(file);
Element bookstore = document.getRootElement();
Iterator storeit = bookstore.elementIterator();
bookList = new ArrayList();
while(storeit.hasNext()){
book = new Book();
Element bookElement = (Element) storeit.next();
//遍历bookElement的属性
List attributes = bookElement.attributes();
for(Attribute attribute : attributes){
if(attribute.getName().equals("id")){
String id = attribute.getValue();//System.out.println(id);
book.setId(Integer.parseInt(id));
}
}
Iterator bookit = bookElement.elementIterator();
while(bookit.hasNext()){
Element child = (Element) bookit.next();
String nodeName = child.getName();
if(nodeName.equals("name")){
//System.out.println(child.getStringValue());
String name = child.getStringValue();
book.setName(name);
}else if(nodeName.equals("author")){
String author = child.getStringValue();
book.setAuthor(author);
}else if(nodeName.equals("year")){
String year = child.getStringValue();
book.setYear(Integer.parseInt(year));
}else if(nodeName.equals("price")){
String price = child.getStringValue();
book.setPrice(Double.parseDouble(price));
}
}
bookList.add(book);
book = null;
}
} catch (DocumentException e) {
e.printStackTrace();
}
return bookList;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("src/res/books.xml");
List bookList = new ReadXMLByDom4j().getBooks(file);
for(Book book : bookList){
System.out.println(book);
}
}
}
文章中的源码可在下面地址下载:
http://github.com/clemontine/XMLParser