1.DOM方式解析XML
Dom解析是将xml文件全部载入到内存,组装成一颗dom树,然后通过节点以及节点之间的关系来解析xml文件,与平台无关,java提供的一种基础的解析XML文件的API,理解较简单,但是由于整个文档都需要载入内存,不适用于文档较大时。
2.SAX方式解析XML
基于事件驱动,逐条解析,适用于只处理xml数据,不易编码,而且很难同时访问同一个文档中的多处不同数据
3.JDOM方式解析XML
简化与XML的交互并且比使用DOM实现更快,仅使用具体类而不使用接口因此简化了API,并且易于使用
4.DOM4j方式解析XML
JDOM的一种智能分支,功能较强大,建议熟练使用
下面贴出第四种方式DOM4j的具体使用:
需要解析的xml:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治马丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童话</name>
<author>安徒生</author>
<year>2004</year>
<price>77</price>
</book>
<book id="3">
<name>think think think</name>
<author>aaa</author>
<year>1997</year>
<price>100</price>
</book>
</bookstore>
工程中引入以下依赖:
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
创建几个bean对象用于存储数据:
package com.qs.bean;
public class Book {
private Integer id;
private String name;
private String author;
private Integer year;
private double price;
public Integer getId() {
return id;
}
public void setId(Integer 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 Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
package com.qs.beanxml;
import com.qs.bean.Book;
import java.util.List;
public class BookStore {
private List<Book> bookstore;
public List<Book> getBookstore() {
return bookstore;
}
public void setBookstore(List<Book> bookstore) {
this.bookstore = bookstore;
}
}
package com.qs.parsexml;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.qs.bean.Book;
import com.qs.beanxml.BookStore;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 用DOM4J方法解析xml文件
*
*/
public class ParseXmlByDom4j {
public static BookStore parseBookStoreXML(File file) {
SAXReader reader = new SAXReader();
BookStore bookStore = new BookStore();
try {
//获取操作文档对象
Document document = reader.read(file);
Element rootElement = document.getRootElement();
//获取这个元素直接子节点的迭代器
Iterator it = rootElement.elementIterator();
//开始解析rootElement下的内容
List<Book> bookList = new ArrayList<>();
Book book = null;
while (it.hasNext()) {
book = new Book();
Element bookElement = (Element) it.next();
//遍历bookElement的所有属性
List<Attribute> attributes = bookElement.attributes();
for (Attribute attribute : attributes) {
if (attribute.getName().equals("id")) {
String id = attribute.getValue();
book.setId(Integer.parseInt(id));
}
}
Iterator bookit = bookElement.elementIterator();
while (bookit.hasNext()) {
Element next = (Element) bookit.next();
String nodeName = next.getName();
String value = next.getStringValue();
if ("name".equals(nodeName)) {
book.setName(value);
} else if ("author".equals(nodeName)) {
book.setAuthor(value);
} else if ("year".equals(nodeName)) {
book.setYear(Integer.parseInt(value));
} else if ("price".equals(nodeName)) {
book.setPrice(Double.parseDouble(value));
}
}
bookList.add(book);
}
bookStore.setBookstore(bookList);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
return bookStore;
}
public static void main(String[] args) {
//注意此处是实际文件的路径
BookStore bookStore = parseBookStoreXML(new File("E:/IDEWorkSpace/IdeaWorkSpace/MyWorkSpace/java_xml/doc/books.xml"));
System.out.println(JSON.toJSONString(bookStore));
}
}
上个文件改进之后:
package com.qs.parsexml;
import com.alibaba.fastjson.JSON;
import com.qs.bean.Book;
import com.qs.beanxml.BookStore;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 用DOM4J方法读取xml文件
* (将上个文件重新封装改进了一下)
*/
public class ParseXmlByDom4j {
public static BookStore parseBookStoreXML(File file) {
SAXReader reader = new SAXReader();
BookStore bookStore = new BookStore();
try {
//获取操作文档对象
Document document = reader.read(file);
Element rootElement = document.getRootElement();
//获取这个元素直接子节点的迭代器
Iterator it = rootElement.elementIterator();
//开始解析rootElement下的内容
List<Book> bookList = new ArrayList<>();
Book book = null;
while (it.hasNext()) {
book = new Book();
Element bookElement = (Element) it.next();
//指定获取某个元素的属性值
String bookId = getValueByAttribute(bookElement, "id");
//设置bookId
if (bookId != null) {
book.setId(Integer.parseInt(bookId));
}
//指定获取book标签下的子标签的内容
String nameValue = getValueByElement(bookElement, "name");
String authorValue = getValueByElement(bookElement, "author");
String yearValue = getValueByElement(bookElement, "year");
String priceValue = getValueByElement(bookElement, "price");
//设置book的其他字段
book.setName(nameValue);
book.setAuthor(authorValue);
book.setYear(Integer.parseInt(yearValue));
book.setPrice(Double.parseDouble(priceValue));
//添加到list中
bookList.add(book);
}
bookStore.setBookstore(bookList);
} catch (DocumentException e) {
e.printStackTrace();
return null;
}
return bookStore;
}
//指定获取某个元素的内容
private static String getValueByElement(Element element, String needElement) {
String value = null;
Iterator it = element.elementIterator();
while (it.hasNext()) {
Element next = (Element) it.next();
String nodeName = next.getName();
if (needElement.equals(nodeName)) {
value = next.getStringValue();
break;
}
}
return value;
}
//获取一个节点元素的某个属性值
private static String getValueByAttribute(Element element, String attribute) {
String value = null;
//遍历bookElement的所有属性
List<Attribute> attributes = element.attributes();
for (Attribute attr : attributes) {
if (attribute.equals(attr.getName())) {
value = attr.getValue();
break;
}
}
return value;
}
public static void main(String[] args) {
//注意此处是实际xml文件的存放路径
BookStore bookStore = parseBookStoreXML(new File("E:/IDEWorkSpace/IdeaWorkSpace/MyWorkSpace/java_xml/doc/books.xml"));
System.out.println(".................................");
System.out.println(JSON.toJSONString(bookStore));
}
}
输出结果:
{
"bookstore": [
{
"author": "乔治马丁",
"id": 1,
"name": "冰与火之歌",
"price": 89.0,
"year": 2014
},
{
"author": "安徒生",
"id": 2,
"name": "安徒生童话",
"price": 77.0,
"year": 2004
},
{
"author": "aaa",
"id": 3,
"name": "think think think",
"price": 100.0,
"year": 1997
}
]
}