以及广义的基于树的处理具有几个优点。首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改。它还可以在任何时候在树中上下导航,而不是像SAX那样是一次性的处理。DOM使用起来也要简单得多。
为 XML 文档的已解析版本定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。
优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;
缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。
废话不多说,上代码:
在main方法中,我们创建了一个domDemo.xml文件,然后进行了解析,打开生成的domDemo.xml文件,我们看到如下:
生成XML成功
-----------------------
解析节点:books
-----------------------
解析节点:book
属性"id"的值为1
-----------------------
解析节点:name
节点值为:书本0
-----------------------
解析节点:price
节点值为:50
-----------------------
解析节点:author
节点值为:作者0
-----------------------
解析节点:book
属性"id"的值为2
-----------------------
解析节点:name
节点值为:书本1
-----------------------
解析节点:price
节点值为:100
-----------------------
解析节点:author
节点值为:作者1
-----------------------
解析节点:book
属性"id"的值为3
-----------------------
解析节点:name
节点值为:书本2
-----------------------
解析节点:price
节点值为:150
-----------------------
解析节点:author
节点值为:作者2