XML解析与DOM解析比较
SAX
1.顺序读入文档并产生相应的事件,可以处理任何大型的XML文档
2.只能对文档按顺序解析,不支持文档的随机访问。
3.只能读取XML文档内容,不能修改
4.开发过程比较复杂,需要自己实现事件处理器
5.可以用SAX创建自己的XML对象模型
例子:Books.xml
<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="201">
<name>鬼吹灯</name>
<author>天下霸上</author>
</book>
<book id="202">
<name>女医明妃传</name>
<author>XXX</author>
</book>
</books>
SaxReader.java代码
package sax;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class SaxReader {
public static void main(String []args) throws Exception{
//1.创建一个XML的工厂对象
SAXParserFactory factory = SAXParserFactory.newInstance();
//2.创建一个XML的解析器的对象
SAXParser parser = factory.newSAXParser();
//3.读取文件并且将其解析成对象
String path = SaxReader.class.getResource("").getPath()+"Books.xml";
//DefaultHanlder:类 SAX解析器执行过程调用的事件的类
//解析器读取文件,并且制定对应事件处理方法MyHanlder
MyHanlder hand = new MyHanlder("book");
parser.parse(path, hand);
//解析器调用了事件处理方法获取了对应标签数据将其封装到MyHanlder中
List<Map<String,String>> list = hand.getList();
//使用foreach遍历list集合
for(Map<String,String> map :list){
//遍历map集合
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
while(it.hasNext()){
String key = it.next();
String value = map.get(key);
System.out.println(key+":"+value);
}
}
}
}
DOM
1.在内存中创建文档树,不适用于大型XML文档。
2.可以随意访问文档树的任何部分,没有次数限制。
3.可以随意修改文档树,从而修改XML文档
4.易于理解,易于开发
5.可以在DOM基础上创建文档树。
例子:
Book.xml
<?xml version="1.0" encoding="gbk"?>
<!-- <!DOCTYPE Book SYSTEM "book.dtd"> -->
<books id="T01" data="N2016">
<book id="B01"><name>茅盾</name>
<author><name>张三</name>
<tel>15672638766</tel>
<email>33333@qq.com</email>
</author><publisher>人民出版社</publisher>
<price>45</price>
</book>
<book id="B02"><name>稻草人日记</name>
<author><name>三毛</name>
<tel>15672638766</tel>
<email>311123@qq.com</email>
</author><publisher>中华出版社</publisher>
<price>39</price>
</book>
<book id="B03"><name>遗忘的花园</name>
<author><name>戴德基</name>
<tel>156778838766</tel>
<email>337899@qq.com</email></author>
<publisher>清华出版社</publisher>
<price>38</price>
</book>
</books>
Book.java
package xml;
import java.util.List;
public class Book {
private String name;
private String publisher;
private List<Author> author;
private String id;
public String toString(){//覆盖该方法。
return name+" "+publisher+" "+price;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public List<Author> getAuthor() {
return author;
}
public void setAuthor(List<Author> author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
private String price;
}
class Author{
private String name;
private String tel;
public String toString(){//覆盖该方法。
return name+" "+tel+" "+email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private String email;
}
Test1.java
package xml;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Test1 {
public static void main(String[] args) {
List<Book> list1 = new ArrayList<Book>();
List<Author> list2 = new ArrayList<Author>();
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
// 2.通过工厂获取的解析器DocumentBuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// 3.通过解析器读取文件,获取文件对应的对象 Document
String path = XmlDomRead.class.getResource("").getPath()
+ "Book.xml";
Document doc = builder.parse(path);
// 4.获得根对象
Element root = doc.getDocumentElement();
System.out.println("根元素:" + root.getTagName());
System.out.println();
// 获取xml中所有的student标签对象
NodeList booknodes = root.getElementsByTagName("book");
// 循环遍历节点
for (int i = 0; i < booknodes.getLength(); i++) {
Node n = booknodes.item(i);
Book book = new Book();
Element stu = (Element) booknodes.item(i);
// System.out.println("第一层:"+n.getNodeName());
// 获取孩子节点
NodeList nodechild = n.getChildNodes();
for (int j = 0; j < nodechild.getLength(); j++) {
Node node = nodechild.item(j);
// System.out.println("第二层:"+node.getNodeName());
if (node.getNodeName() == "author") {
Author author = new Author();
NodeList nodechilds = node.getChildNodes();
for (int t = 0; t < nodechilds.getLength(); t++) {
Node nodes = nodechilds.item(t);
if (nodes.getNodeName() == "name") {
// System.out.println("author的第er层"+node.getNodeName());
author.setName(nodes.getTextContent());
// System.out.println(author.getName());
} else if (nodes.getNodeName() == "tel") {
// System.out.println("author的第er层"+node.getNodeName());
author.setTel(nodes.getTextContent());
} else if (nodes.getNodeName() == "email") {
// System.out.println("author的第er层"+node.getNodeName());
author.setEmail(nodes.getTextContent());
}
}
list2.add(author);
book.setAuthor(list2);
} else if (node.getNodeName() == "name") {
book.setName(node.getTextContent());
} else if (node.getNodeName() == "publisher") {
book.setPublisher(node.getTextContent());
// System.out.println(book.getPublisher());
} else if (node.getNodeName() == "price") {
book.setPrice(node.getTextContent());
// System.out.println(book.getPrice());
}else if(stu.getNodeName()== "book"){
book.setId(stu.getAttribute("id"));
}
}
list1.add(book);// 添加进集合中。
}
/*for(int s = 0;s < list1.size(); s++){
Iterator iter = list1.iterator();// 使用跌代器遍历集合元素。
System.out.println("作者名:"+list2.get(s).getName());
System.out.println("作者电话号码:"+list2.get(s).getTel());
System.out.println("作者Email:"+list2.get(s).getEmail());
while(iter.hasNext()) {
Book ss = (Book) iter.next();
System.out.println(ss);
System.out.println();
}
}*/
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for(int s = 0;s < list1.size(); s++){
System.out.println("书ID:"+list1.get(s).getId());
System.out.println("书名:"+list1.get(s).getName());
System.out.println("作者名:"+list2.get(s).getName());
System.out.println("作者电话号码:"+list2.get(s).getTel());
System.out.println("作者Email:"+list2.get(s).getEmail());
System.out.println("价格:"+list1.get(s).getPrice());
System.out.println("出版社:"+list1.get(s).getPublisher());
System.out.println();
}
}
}