面试题:请解释DOM与SAX的区别?
DOM(Document Object Model,文档对象模型):是W3C定义的标记语言的标准操作,
在DOM操作之中需要将所有的标记转换为DOM树进行处理,并且使用DOM可以实现数据的读取与修改功能。
SAX(Sample API for XML,简单XML解析工具):采用顺序式的方式进行文档数据的读取,本身适合于读取
大型数据,但是SAX不允许修改文档。
认识DOM4J
DOM4J产生背景
DOM4J实现数据的操作
这个工具即有SAX解析的优点,也有返回处DOM解析的优点
使用DOM4J,首先要清楚哪些类可以完成XML文件的操作,这个包属于第三方开发程序
所以需要将这个开发包配置到项目的CLASSPATH中
1.DocumentHelper创建工具类:
在DOM操作中如果要想使用Document,需要DocumentBuilderFactory与DocumentBuilder两个类
但是这两个类的使用太麻烦了,所以DOM4J提供了一个org.dom4j.DocumentHelper
主要的方法有:
创建文档对象:public static Document createDocument()
创建文档同时设置根元素:public static Document createDocument(Element rootElement)
创建元素:public static Element createElement(java.lang.String name)
创建属性:public static Attribute createAttribute(Element owner,
QName qname,
java.lang.String value)
使用DOM4J创建的时候就没有必要去思考Text了。
2.Document操作接口:org.dom4j.Document(是Branch子接口,Branch是Node的子接口)
在整个XML文件里面一定会存在有Document的概念,在这个接口里面定义有如下方法:
取得根元素:public Element getRootElement()
设置根元素:public void setRootElement(Element rootElement)
设置XML文件编码:public void setXMLEncoding(java.lang.String encoding)
3.观察org.dom4j.Branch接口的方法:
增加节点对象:public void add(Node node)
增加元素:public Element addElement(java.lang.String name)
取得指定索引的节点:public Node node(int index)
throws java.lang.IndexOutOfBoundsException
节点个数:public int nodeCount()
删除节点:public boolean remove(Node node)
4.观察org.dom4j.Node接口的方法
取得父节点:public Element getParent()
取得节点的内容:public java.lang.String getText()
设置节点的内容:public void setText(java.lang.String text)
5.数据格式化输出类:org.dom4j.io.OutputFormat
紧凑型输出:public static OutputFormat createCompactFormat()
漂亮的输出:public static OutputFormat createPrettyPrint()
设置输出编码:public void setEncoding(java.lang.String encoding)
6.输出数据类:org.dom4j.io.XMLWriter
构造方法:public XMLWriter(OutputFormat format)
throws java.io.UnsupportedEncodingException
内容输出:public void write(Document doc)
throws java.io.IOException