books.xml
冰与火之歌
乔治马丁
2014
88
安徒生童话
2004
83
English
DOM解析
import java.io.IOException;
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.xml.sax.SAXException;
public class Dom {
public static void main(String[] args) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 创建DocumentBuilder对象
DocumentBuilder db = dbf.newDocumentBuilder();
// 通过DocumentBuilder对象的parse方法加载books.xml文件到当前目录下
Document document = db.parse("books.xml");
// 获取所有book节点的集合
NodeList bookList = document.getElementsByTagName("book");
// 通过nodeList的getLength()可以获取bookList的长度
System.out.println("一共有" + bookList.getLength() + "本书");
// 遍历每一个book节点
for(int i=0; i之间的空白也算是一个子节点(是text类型的子节点),所以会输出有9个子节点
System.out.println("第" + (i + 1) + "本书一共有" + childNodes.getLength() + "个子节点");
// 遍历childNodes获取每个节点的节点名和节点值
for(int k=0; kaa冰与火之歌将会输出“aa冰与火之歌”
// System.out.println("--节点值是:" + childNodes.item(k).getTextContent());
}
}
System.out.println("==============结束遍历第" + (i + 1) + "本书的内容================");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SAX解析
book.java
public class Book {
private int id;
private String name;
private String author;
private String year;
private String price;
private String language;
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 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;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
SAXHandler.java
public class SAXHandler extends DefaultHandler {
private int index;
private Book book;
private List bookList = new ArrayList<>();
private String value;
public List getBookList() {
return bookList;
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
System.out.println("=============开始解析文档==================");
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
System.out.println("=============结束解析文档==================");
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
if(qName.equals("book")) {
book = new Book();
index++;
System.out.println("=============开始解析第" + (index) + "本书==================");
int id = Integer.valueOf(attributes.getValue("id"));
book.setId(id);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if(qName.equals("name")) {
book.setName(value);
} else if(qName.equals("author")) {
book.setAuthor(value);
} else if(qName.equals("year")) {
book.setYear(value);
} else if(qName.equals("price")) {
book.setPrice(value);
} else if(qName.equals("language")) {
book.setLanguage(value);
} else if(qName.equals("book")) {
bookList.add(book);
book = null;
System.out.println("=============结束解析第" + (index) + "本书==================");
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
value = new String(ch, start, length);
}
}
SAX.java
public class SAX {
public static void main(String[] args) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
SAXHandler handler = new SAXHandler();
parser.parse("books.xml", handler);
List bookList = handler.getBookList();
for(Book book : bookList) {
System.out.println(book.getId());
System.out.println(book.getName());
System.out.println(book.getAuthor());
System.out.println(book.getYear());
System.out.println(book.getPrice());
System.out.println(book.getLanguage());
System.out.println("===finish=====");
}
} catch (ParserConfigurationException | SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JDOM解析(导jar包)
public class JDOM {
public static void main(String[] args) {
List bookEntityList = new ArrayList<>();
Book bookEntity = null;
try {
// 创建SAXBuilder对象
SAXBuilder saxBuilder = new SAXBuilder();
// 2.创建一个输入流,将xml文件加载到输入流中
InputStream in = new FileInputStream("books.xml");
// 3.通过saxBuilder的build方法,将输入流加载到saxBuilder中
Document document = saxBuilder.build(in);
// 4.通过document对象获取xml文件的根节点
Element rootElement = document.getRootElement();
// 5.获取根节点下的子节点的List集合
List bookList = rootElement.getChildren();
for(Element book : bookList) {
bookEntity = new Book();
System.out.println("===========开始解析第" + (bookList.indexOf(book) + 1) + "本书============");
// 解析book的属性集合
List attrList = book.getAttributes();
for(Attribute attr : attrList) {
String attrName = attr.getName();
String attrValue = attr.getValue();
System.out.println("属性名:" + attrName + "----属性值:" + attrValue);
if(attrName.equals("id")) {
bookEntity.setId(Integer.valueOf(attrValue));
}
}
// String attrValue = book.getAttributeValue("id");
// System.out.println("属性名:id" + "----属性值:" + attrValue);
List bookChildren = book.getChildren();
for(Element bookChild : bookChildren) {
String nodeName = bookChild.getName();
String nodeValue = bookChild.getValue();
System.out.println("节点名:" + nodeName + "----节点值:" + nodeValue);
if(nodeName.equals("name")) {
bookEntity.setName(nodeValue);
} else if(nodeName.equals("author")) {
bookEntity.setAuthor(nodeValue);
} else if(nodeName.equals("year")) {
bookEntity.setYear(nodeValue);
} else if(nodeName.equals("price")) {
bookEntity.setPrice(nodeValue);
} else if(nodeName.equals("language")) {
bookEntity.setLanguage(nodeValue);
}
}
System.out.println("===========结束解析第" + (bookList.indexOf(book) + 1) + "本书============");
bookEntityList.add(bookEntity);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(bookEntityList);
}
}
book.java同上
DOM4J解析(导jar包)
public class DOM4J {
public static void main(String[] args) {
int index = 0;
// 创建SAXReader对象
SAXReader saxReader = new SAXReader();
try {
// 通过saxReader的read方法加载books.xml对象
Document document = saxReader.read(new File("books.xml"));
// 获取根节点
Element bookStore = document.getRootElement();
// 获取迭代器
Iterator it = bookStore.elementIterator();
while(it.hasNext()) {
index++;
System.out.println("===========开始解析第" + index + "本书=================");
Element book = it.next();
List attrList = book.attributes();
for(Attribute attr : attrList) {
String name = attr.getName();
String value = attr.getValue();
System.out.println("属性名:" + name + "--属性值:" + value);
}
Iterator it2 = book.elementIterator();
while(it2.hasNext()) {
Element node = it2.next();
String name = node.getName();
String value = node.getStringValue();
System.out.println("节点名:" + name + "--节点值:" + value);
}
System.out.println("===========结束解析第" + index + "本书=================");
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4种解析方法的分析
DOM:
平台无关的官方解析方式,不只在java中适用
优点: 1.形成了树结构,直观好理解,代码更易编写
2.解析过程中树结构保留在内存中,方便修改
缺点: 当xml文件较大时,对内存耗费比较大,容易影响解析性能并造成内存溢出
SAX:
基于事件驱动的解析方法,平台无关的官方解析方式,不只在java中适用
优点: 1.采用事件驱动模式,对内存耗费比较小
2.适用于只需要处理xml中数据时
缺点: 1.不易编码
2.很难同时访问同一个xml中的多处不同数据
JDOM:
在SAX上扩展出来的解析方法,只有java中能够使用
优点: 1.仅使用具体类而不使用接口
2.API大量使用了Collections类
DOM4J:
在SAX上扩展出来的解析方法,只有java中能够使用
优点: 1.JDOM的一种智能分支,它合并了许多超出基本xml文档表示的内容
2.DOM4J使用接口和抽象基本类方法,是一个优秀的Java XML API
关于解析速度:
对于上述的books.xml
解析速度SAX>DOM>DOM4J>JDOM
book.xml文件小,所以解析速度DOM>DOM4J
DOM4J比起DOM优势在于能更快解析较复杂的xml文件,不妨增加books.xml的内容试试看
https://github.com/LuJN/SAXTest