1.DOM和SAX的不同:
1. DOM是基于内存的,不管文件有多大,都会将所有的内容预先装载到内存中。从而消耗很大的内存空间。而SAX是基于事件的。当某个事件被触发时,才获取相应的XML的部分数据,从而不管XML文件有多大,都只占用了少量的内存空间。
2. DOM可以读取XML也可以向XML文件中插入数据,而SAX却只能对XML进行读取,而不能在文件中插入数据。这也是SAX的一个缺点。
3.SAX的另一个缺点:DOM我们可以指定要访问的元素进行随机访问,而SAX则不行。SAX是从文档开始执行遍历的。并且只能遍历一次。也就是说我们不能随机的访问XML文件,只能从头到尾的将XML文件遍历一次(当然也可以中间截断遍历)。
DOM和SAX对XML文件的解析:
1. 在使用DOM解析XML时,我们首先需要通过DocumentBuilderFactory这个类得到一个工厂的API,使应用程序能够从XML文档获取 生成对象树的解析器。通过此类的 newinstance() 方法我们可以获得此类的一个新实例。然后通过创建DocumentBuilder的实例使其从XML文档中获取DOM文档实例。 DocumentBuilder的实例我们可以通过DocumentBuilderFactory类的newDocumentBuilder()方法得 到。之后就通过DocumentBuilder类的parse(InputStream is)方法将给定文件的内容解析为一个XML文档,并且返回一个新的DOM Document 对象。
2.JDom = Dom的可修改性 + Sax的可读取性(http://www.jdom.org/downloads/)
JDom的输出:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.*;
import org.jdom2.output.XMLOutputter;
public class JdomDemo {
public static void main(String[] args) throws FileNotFoundException, IOException{
Element addresslist = new Element("addresslist");
Element linkman = new Element("linkman");
Element name = new Element("name");
Element email = new Element("email");
Attribute id = new Attribute("id","xiaopang");
Document document = new Document(addresslist);
name.setText("小胖");
name.setAttribute(id);
email.setText("4315143@qq.com");
linkman.addContent(name);
linkman.addContent(email);
addresslist.addContent(linkman);
XMLOutputter outputter =new XMLOutputter();
// outputter.setFormat(outputter.getFormat().setEncoding("GBK")); 设置编码
outputter.output(document, new FileOutputStream(new File("src/jdomTest.xml")));
}
}
JDom的读取主要还是用SAX:
import java.io.File;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class JDomRead {
public static void main(String[] args) throws JDOMException, IOException{
SAXBuilder builder = new SAXBuilder();
Document read_doc = builder.build(new File("src/domDemo.xml"));
Element root = read_doc.getRootElement();
java.util.List<Element> list = root.getChildren("linkman");
for(int i=0;i < list.size();i++){
Element element = ((java.util.List<Element>) list).get(i);
String name = element.getChildText("name");
String email = element.getChildText("email");
System.out.println("姓名:"+name+"Email:"+email);
}
}
}