测试所用到的bean
<--------------------Bean-start---------------------->
package org.wcy.model;
/**
* xml解析测试类
*
Title : Book
*
Description :
*
DevelopTools : Eclipse_x64_v4.8.0
*
DevelopSystem : Windows 10
*
Company : org.wcy
* @author : WangChenYang
* @date : 2018年11月8日 上午9:59:42
* @version : 0.0.1
*/
public class Book {
private int id;
private String name;
private String author;
private int year;
private double price;
public Book() {
}
public Book(int id, String name, String author, int year, double price) {
super();
this.id = id;
this.name = name;
this.author = author;
this.year = year;
this.price = price;
}
public void setAttribute(String attributeName,Object value) {
if("id".equals(attributeName)) {
this.id = Integer.parseInt(value.toString());
}
if("name".equals(attributeName)) {
this.name = value.toString();
}
if("author".equals(attributeName)) {
this.author = value.toString();
}
if("year".equals(attributeName)) {
this.year = Integer.parseInt(value.toString());
}
if("price".equals(attributeName)) {
this.price = Double.parseDouble(value.toString());
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Book [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", author=");
builder.append(author);
builder.append(", year=");
builder.append(year);
builder.append(", price=");
builder.append(price);
builder.append("]");
return builder.toString();
}
}
<--------------------Bean-end---------------------->
测试使用的xml文件
<--------------------xmlFile-start---------------------->
冰与火之歌
乔治马丁
2014
89
安徒生童话
安徒生
2004
77
鲁宾孙漂流记
。。。
1999
99.12
<--------------------xmlFile-end---------------------->
DOM方法读取
<--------------------DOM-start---------------------->
package org.wcy.XMLparse;
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.Node;
import org.w3c.dom.NodeList;
import org.wcy.model.Book;
/**
* 通过dom读取xml文件
*
Title : DOM
*
Description :
*
DevelopTools : Eclipse_x64_v4.8.0
*
DevelopSystem : Windows 10
*
Company : org.wcy
* @author : WangChenYang
* @date : 2018年11月8日 上午10:03:27
* @version : 0.0.1
*/
public class DOM {
//document解析器工厂
private static DocumentBuilderFactory docBuiFactory = null;
//document解析器可以通过documentBuiderFactory的newDocumentBuilder()函数获取
private static DocumentBuilder docBuilder = null;
//document对象可以通过documentBuilder的newDocumentBuilder()函数获取
private static Document doc = null;
//自定义对象book的集合用来存储xml获取的book对象
private static List
books = null;
//静态代码块用来初始化静态属性,只会在类的第一次加载执行一次
static {
try {
//初始化documentBuilderFactory
docBuiFactory = DocumentBuilderFactory.newInstance(); //newInstance通过反射机制创建DocumentBuilderFactory的实现类
//初始化documentBuilder
docBuilder = docBuiFactory.newDocumentBuilder(); //通过DocumentBuilderFactoryImpl的newDocumentBuilder()函数返回DocumentBuilder对象
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static List getBooks(String fileURL) throws Exception {
//将给定的url的内容解析为一个xml文档,并返回document对象
doc = docBuilder.parse(fileURL);
//按顺序获取xml内所有book元素节点
NodeList bookList = doc.getElementsByTagName("book");
books = new ArrayList();
//遍历books
for(int i=0;i Book book = new Book();
//从节点集中获取i个book节点
Node node = bookList.item(i);
//获取第一个节点内的所有属性
NamedNodeMap nameNodeMap = node.getAttributes();
//获取节点内名为id的属性的值
String id = nameNodeMap.getNamedItem("id").getTextContent();
//将id属性存储到自定义对象book内
book.setId(Integer.parseInt(id));
//获取book节点内的子节点
NodeList childList = node.getChildNodes();
/*list*/
//将一个book里面的所有文本内容存入集合
// ArrayList bookContents = new ArrayList<>();
// for(int j=0;j // Node childNode = childList.item(j);
// //获取子节点内的文本内容
// String content = childNode.getTextContent();
// //获取节点名
// String name = childNode.getNodeName();
// //System.out.println(j+","+name+"="+content);
// //判断是否为空格和回车节点
// if(!"#text".equals(name)) {
// bookContents.add(content);
// }
// }
// book.setName(bookContents.get(0));
// book.setAuthor(bookContents.get(1));
// book.setYear(Integer.parseInt(bookContents.get(2)));
// book.setPrice(Double.parseDouble(bookContents.get(3)));
/*map*/
//将一个book里面的所有文本内容存入map
// Map map = new HashMap<>();
// for(int j=0;j // Node childNode = childList.item(j);
// //获取子节点内的文本内容
// Object content = childNode.getTextContent();
// //获取节点名
// String name = childNode.getNodeName();
// //判断是否为空格和回车节点
// if(!"#text".equals(name)) {
// map.put(name, content);
// }
// }
// book.setName((String)map.get("name"));
// book.setAuthor((String)map.get("author"));
// book.setYear(Integer.parseInt(map.get("year").toString()));
// book.setPrice(Double.parseDouble(map.get("price").toString()));
/*函数判断*/
for(int j=0;j Node childNode = childList.item(j);
//获取子节点内的文本内容
Object content = childNode.getTextContent();
//获取节点名
String name = childNode.getNodeName();
//判断是否为空格和回车节点
if(!"#text".equals(name)) {
book.setAttribute(name, content);
}
}
books.add(book);
}
return books;
}
public static void main(String[] args) {
long s = System.currentTimeMillis();
String fileURL = "src/main/resources/text.xml";
try {
List list = DOM.getBooks(fileURL);
for (Book book : list) {
System.out.println(book.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long o = System.currentTimeMillis();
System.out.println(o-s);
}
}
<--------------------DOM-end---------------------->
SAX读取
<--------------------SAX-start---------------------->
自定义handle,用SAX解析xml文件时需要的handler
<--------------------SAXParseHandler -start---------------------->
package org.wcy.XMLparse;
import java.util.ArrayList;
import java.util.List;
import org.wcy.model.Book;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* 自定义handler
* 用SAX解析xml文件时需要的handler
*
Title : SAXParseHandler
* Description :
* DevelopTools : Eclipse_x64_v4.8.0
* DevelopSystem : Windows 10
* Company : org.wcy
* @author : WangChenYang
* @date : 2018年11月8日 上午11:23:13
* @version : 0.0.1
*/
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;
}
}
<--------------------SAXParseHandler -end---------------------->
读取xml的类
<--------------------ReadXmlBySAX-start---------------------->
package org.wcy.XMLparse;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.wcy.model.Book;
/**
* 用SAX方式读取xml文件
*
Title : ReadXmlBySAX
* Description :
* DevelopTools : Eclipse_x64_v4.8.0
* DevelopSystem : Windows 10
* Company : org.wcy
* @author : WangChenYang
* @date : 2018年11月8日 上午11:50:17
* @version : 0.0.1
*/
public class ReadXmlBySAX {
private static List books = 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) {
long s = System.currentTimeMillis();
try {
books = new ReadXmlBySAX().getBooks("src/main/resources/text.xml");
for(Book book:books){
System.out.println(book);
}
} catch (Exception e) {
e.printStackTrace();
}
long o = System.currentTimeMillis();
System.out.println(o-s);
}
}
<--------------------ReadXmlBySAX-end---------------------->
<--------------------SAX-end---------------------->
用JDOM方式读取
<--------------------JDOM-start---------------------->
org.jdom
jdom2
2.0.6
package org.wcy.XMLparse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.wcy.model.Book;
/**
* 用JDOM方式读取xml文件
*
Title : JDOM
* Description :
* DevelopTools : Eclipse_x64_v4.8.0
* DevelopSystem : Windows 10
* Company : org.wcy
* @author : WangChenYang
* @date : 2018年11月8日 上午11:50:07
* @version : 0.0.1
*/
public class JDOM {
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
long s = System.currentTimeMillis();
String fileName = "src/main/resources/text.xml";
List books= new JDOM().getBooks(fileName);
for(Book book : books){
System.out.println(book);
}
long o = System.currentTimeMillis();
System.out.println(o-s);
}
}
<--------------------JDOM-end---------------------->
DOM4J方式读取
<--------------------DOM4J-start---------------------->
org.dom4j
dom4j
2.1.1
package org.wcy.XMLparse;
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 org.wcy.model.Book;
/**
* 用DOM4J方法读取xml文件
*
Title : DOM4J
* Description :
* DevelopTools : Eclipse_x64_v4.8.0
* DevelopSystem : Windows 10
* Company : org.wcy
* @author : WangChenYang
* @date : 2018年11月8日 上午11:50:00
* @version : 0.0.1
*/
public class DOM4J {
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
long s = System.currentTimeMillis();
File file = new File("src/main/resources/text.xml");
List bookList = new DOM4J().getBooks(file);
for(Book book : bookList){
System.out.println(book);
}
long o = System.currentTimeMillis();
System.out.println(o-s);
}
}
<--------------------DOM4J-end---------------------->