`

org.w3c.dom(java dom)解析XML文档

阅读更多

org.w3c.dom(java dom)解析XML文档

位于org.w3c.dom操作XML会比较简单,就是将XML看做是一颗树,DOM就是对这颗树的一个数据结构的描述,但对大型XML文件效果可能会不理想

首先来了解点Java DOM 的 API:
1.解析器工厂类:DocumentBuilderFactory

创建的方法:DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

2.解析器:DocumentBuilder

创建方法:通过解析器工厂类来获得 DocumentBuilder db = dbf.newDocumentBuilder();

3.文档树模型Document

创建方法:a.通过xml文档 Document doc = db.parse("bean.xml");  b.将需要解析的xml文档转化为输入流 InputStream is = new FileInputStream("bean.xml");

 Document doc = db.parse(is); 

Document对象代表了一个XML文档的模型树,所有的其他Node都以一定的顺序包含在Document对象之内,排列成一个树状结构,以后对XML文档的所有操作都与解析器无关,

直接在这个Document对象上进行操作即可;

 包含的方法:

4.节点列表类NodeList

NodeList代表了一个包含一个或者多个Node的列表,根据操作可以将其简化的看做为数组

5.节点类Node

Node对象是DOM中最基本的对象,代表了文档树中的抽象节点。但在实际使用中很少会直接使用Node对象,而是使用Node对象的子对象Element,Attr,Text等

6.元素类Element

是Node类最主要的子对象,在元素中可以包含属性,因而Element中有存取其属性的方法

7.属性类Attr

代表某个元素的属性,虽然Attr继承自Node接口,但因为Attr是包含在Element中的,但并不能将其看做是Element的子对象,因为Attr并不是DOM树的一部

基本的知识就到此结束,更加具体的大家可以参阅JDK API文档

 

实战:

1.使用DOM来遍历XML文档中的全部内容并且插入元素:

school.xml文档:

复制代码
<?xml version = "1.0" encoding = "utf-8"?>
<School>
    <Student>
        <Name>沈浪</Name>
        <Num>1006010022</Num>
        <Classes>信管2</Classes>
        <Address>浙江杭州3</Address>
        <Tel>123456</Tel>
    </Student>
    <Student>
        <Name>沈1</Name>
        <Num>1006010033</Num>
        <Classes>信管1</Classes>
        <Address>浙江杭州4</Address>
        <Tel>234567</Tel>
    </Student>
    <Student>
        <Name>沈2</Name>
        <Num>1006010044</Num>
        <Classes>生工2</Classes>
        <Address>浙江杭州1</Address>
        <Tel>345678</Tel>
    </Student>
    <Student>
        <Name>沈3</Name>
        <Num>1006010055</Num>
        <Classes>电子2</Classes>
        <Address>浙江杭州2</Address>
        <Tel>456789</Tel>
    </Student>
</School>
复制代码

DomDemo.java

复制代码
package xidian.sl.dom;

import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class DomDemo {
    /**
     * 遍历xml文档
     * */
    public static void queryXml(){
        try{
            //得到DOM解析器的工厂实例
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //从DOM工厂中获得DOM解析器
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //把要解析的xml文档读入DOM解析器
            Document doc = dbBuilder.parse("src/xidian/sl/dom/school.xml");
            System.out.println("处理该文档的DomImplementation对象  = "+ doc.getImplementation());
            //得到文档名称为Student的元素的节点列表
            NodeList nList = doc.getElementsByTagName("Student");
            //遍历该集合,显示结合中的元素及其子元素的名字
            for(int i = 0; i< nList.getLength() ; i ++){
                Element node = (Element)nList.item(i);
                System.out.println("Name: "+ node.getElementsByTagName("Name").item(0).getFirstChild().getNodeValue());
                System.out.println("Num: "+ node.getElementsByTagName("Num").item(0).getFirstChild().getNodeValue());
                System.out.println("Classes: "+ node.getElementsByTagName("Classes").item(0).getFirstChild().getNodeValue());
                System.out.println("Address: "+ node.getElementsByTagName("Address").item(0).getFirstChild().getNodeValue());
                System.out.println("Tel: "+ node.getElementsByTagName("Tel").item(0).getFirstChild().getNodeValue());
            }
            
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    /**
     * 向已存在的xml文件中插入元素
     * */
    public static void insertXml(){
        Element school = null;
        Element student = null;
        Element name = null;
        Element num = null;
        Element classes = null;
        Element address = null;
        Element tel = null;
        try{
            //得到DOM解析器的工厂实例
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //从DOM工厂中获得DOM解析器
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //把要解析的xml文档读入DOM解析器
            Document doc = dbBuilder.parse("src/xidian/sl/dom/school.xml");
            //得到文档名称为Student的元素的节点列表
            NodeList nList = doc.getElementsByTagName("School");
            school = (Element)nList.item(0);
            //创建名称为Student的元素
            student = doc.createElement("Student");
            //设置元素Student的属性值为231
            student.setAttribute("examId", "23");
            //创建名称为Name的元素
            name = doc.createElement("Name");
            //创建名称为 香香 的文本节点并作为子节点添加到name元素中
            name.appendChild(doc.createTextNode("香香"));
            //将name子元素添加到student中
            student.appendChild(name);
            /**
             * 下面的元素依次加入即可
             * */
            num = doc.createElement("Num");
            num.appendChild(doc.createTextNode("1006010066"));
            student.appendChild(num);
            
            classes = doc.createElement("Classes");
            classes.appendChild(doc.createTextNode("眼视光5"));
            student.appendChild(classes);
            
            address = doc.createElement("Address");
            address.appendChild(doc.createTextNode("浙江温州"));
            student.appendChild(address);
            
            tel = doc.createElement("Tel");
            tel.appendChild(doc.createTextNode("123890"));
            student.appendChild(tel);
            
            //将student作为子元素添加到树的根节点school
            school.appendChild(student);
            //将内存中的文档通过文件流生成insertSchool.xml,XmlDocument位于crison.jar下
            ((XmlDocument)doc).write(new FileOutputStream("src/xidian/sl/dom/insertSchool.xml"));
            System.out.println("成功");
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }    
    }
    public static void main(String[] args){
        //读取
        DomDemo.queryXml();
        //插入
        DomDemo.insertXml();
    }
}
复制代码

 

运行后结果:

 


然后到目录下查看生成的xml文件:

打开查看内容:

上面添加元素后输出的文件与之前的文件不是同一个文件,如果需要输出到原文件中,那么只要将路径改为原文间路径即可:src/xidian/sl/dom/school.xml

 2.创建XML过程与插入过程相似,就是Document需要创建

复制代码
package xidian.sl.dom;

import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class CreateNewDom {
    /**
     * 创建xml文档
     * */
    public static void createDom(){
        Document doc;
        Element school,student;
        Element name = null;
        Element num = null;
        Element classes = null;
        Element address = null;
        Element tel = null;
        try{
            //得到DOM解析器的工厂实例
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //从DOM工厂中获得DOM解析器
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //创建文档树模型对象
            doc = dbBuilder.newDocument();
            if(doc != null){
                //创建school元素
                school = doc.createElement("School");
                //创建student元素
                student = doc.createElement("Student");
                //设置元素Student的属性值为231
                student.setAttribute("examId", "23");
                //创建名称为Name的元素
                name = doc.createElement("Name");
                //创建名称为 香香 的文本节点并作为子节点添加到name元素中
                name.appendChild(doc.createTextNode("香香"));
                //将name子元素添加到student中
                student.appendChild(name);
                /**
                 * 下面的元素依次加入即可
                 * */
                num = doc.createElement("Num");
                num.appendChild(doc.createTextNode("1006010066"));
                student.appendChild(num);
                
                classes = doc.createElement("Classes");
                classes.appendChild(doc.createTextNode("眼视光5"));
                student.appendChild(classes);
                
                address = doc.createElement("Address");
                address.appendChild(doc.createTextNode("浙江温州"));
                student.appendChild(address);
                
                tel = doc.createElement("Tel");
                tel.appendChild(doc.createTextNode("123890"));
                student.appendChild(tel);
                
                //将student作为子元素添加到树的根节点school
                school.appendChild(student);
                //添加到文档树中
                doc.appendChild(school);
                //将内存中的文档通过文件流生成insertSchool.xml,XmlDocument位于crison.jar下
                ((XmlDocument)doc).write(new FileOutputStream("src/xidian/sl/dom/createSchool.xml"));
                System.out.println("创建成功");
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        CreateNewDom.createDom();
    }
}
复制代码

运行结果:

DOM的操作应该还是非常简单明了的,掌握了没哦。

 

 

 

 

 

 

希望多多交流,多多关注,共同成就梦想
 
posted on 2012-05-11 00:14 发表是最好的记忆 阅读(4817) 评论(29) 编辑 收藏
 

评论:
 
#1楼 2013-02-24 17:19 | turtlegood  
请问“包含的方法”下面的那些方法的javadoc您是在哪里找到的,哪里有中文的?
  
#2楼[楼主] 2013-02-24 17:27 | 发表是最好的记忆  
@turtlegood
你可以去网上找一个中文的JDK api,或者加我qq,我传给你;
544921534
  
#3楼 2013-02-26 12:21 | turtlegood  
你好,你的qq我加不了又验证问题要不你发到我邮箱turtlegood@163.com或者1091373496@qq.com
  
#4楼 2013-02-27 18:08 | turtlegood  
您好,为什么我的eclipse(ubuntu上),没有crison.jar,就是没有org.apache.crison没有这个目录,请问怎么解决?
  
#5楼[楼主] 2013-02-27 19:00 | 发表是最好的记忆  
@turtlegood
crison.jar是要自己导入的,放到 lib目录下,并不是自带的,我发你吧
  
#6楼 2013-02-27 19:04 | turtlegood  
@
谢谢您!
  
#7楼[楼主] 2013-02-27 19:05 | 发表是最好的记忆  
@turtlegood
互相学习嘛
  
#8楼 2013-02-27 19:33 | turtlegood  
搞定!谢谢!
  
#9楼[楼主] 2013-02-27 19:35 | 发表是最好的记忆  
@turtlegood
那就好,哈哈
  
#10楼 2013-03-01 16:47 | turtlegood  
请问您的代码插件是从哪里来得?
  
#11楼[楼主] 2013-03-01 20:48 | 发表是最好的记忆  
@turtlegood
在新增随笔的编辑器上不是有个插入代码的功能
  
#12楼 2013-03-03 18:54 | turtlegood  
@发表是最好的记忆
有吗?看了一边没找到
  
#13楼 2013-03-03 18:55 | turtlegood  
@发表是最好的记忆
看到了,,,,,,,,,居然是插入代码我还以为是插入html呢。。。。。。
  
#14楼 2013-03-08 19:18 | turtlegood  
您好,请问crimson您是怎么导入的?我一导入就出错,问题网址:http://www.apkbus.com/forum.php?mod=viewthread&tid=99791&page=1#pid841263
  
#15楼[楼主] 2013-03-09 11:14 | 发表是最好的记忆  
@turtlegood
直接放到WEB-INF的lib目录下就可以;
  
#16楼 2013-03-09 16:00 | turtlegood  
@发表是最好的记忆
请问您不是使用eclipse吗?web-inf目录在哪里?
  
#17楼 2013-03-09 16:04 | turtlegood  
@发表是最好的记忆
我建立的是android app项目不是web项目啊
  
#19楼 2013-03-09 16:24 | turtlegood  
@发表是最好的记忆
您好,我的xml不需要网络,在本地就可以了。没太看懂那个网址,我不须要用到网络
  
#20楼 2013-03-09 16:28 | turtlegood  
@发表是最好的记忆
我吧包放在libs底下也没用
  
#21楼 2013-03-09 16:38 | turtlegood  
@发表是最好的记忆
[2013-03-09 16:37:52 - SelectToDo] Dx 1 error; aborting
[2013-03-09 16:37:52 - SelectToDo] Conversion to Dalvik format failed with error 1
它仍然说这个错误
[2013-03-09 16:29:02 - SelectToDo] Dx
trouble processing "javax/xml/parsers/DocumentBuilder.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

[2013-03-09 16:29:02 - SelectToDo] Dx 1 error; aborting
[2013-03-09 16:29:02 - SelectToDo] Conversion to Dalvik format failed with error 1
[2013-03-09 16:29:21 - SelectToDo] Dx
trouble processing "javax/xml/parsers/DocumentBuilder.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intention
  
#22楼 2013-03-09 16:38 | turtlegood  
ally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

[2013-03-09 16:29:21 - SelectToDo] Dx 1 error; aborting
[2013-03-09 16:29:21 - SelectToDo] Conversion to Dalvik format failed with error 1
[2013-03-09 16:37:52 - SelectToDo] Dx
trouble processing "javax/xml/parsers/DocumentBuilder.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.
  
#23楼 2013-03-09 16:39 | turtlegood  
@发表是最好的记忆
您使用什么版本的android?我前面用2.1,后来用4.0都不行。它好像说的是定义了核的什么
  
#24楼[楼主] 2013-03-09 16:42 | 发表是最好的记忆  
@turtlegood
这个跟版本没有关系的
  
#25楼 2013-03-09 17:28 | turtlegood  
@发表是最好的记忆
那个英文的错误提示好像是说,crimson调用了javax.xml.parsers,说不应该让一个不是核心库的库调用系统内容?
我是android app工程,请问又什么解决方法吗?
  
#26楼[楼主] 2013-03-09 18:10 | 发表是最好的记忆  
@turtlegood
你还是网上查下吧 这个很难说的
  
#27楼 2013-03-09 19:41 | turtlegood  
@发表是最好的记忆
就是查不到。。。
  
#28楼 2013-03-09 19:41 | turtlegood  
@发表是最好的记忆
你是建立web工程吗?
  
#29楼 2013-03-15 18:03 | xlc121114  
你好,非常感谢你分享的这个文章,写的非常好,我想要crison.jar这个架包,加你QQ验证没通过,可以发我邮箱吗?348492688@qq.com 谢谢啦
 
分享到:
评论

相关推荐

    w3c-dom.jar 包

    w3c-dom.jar 包 dom解析xml使用 包 免积分下载

    java SE API

    JavaTM 2 Platform Standard Ed. 5.0 ...org.omg.stub.java.rmi org.w3c.dom org.w3c.dom.bootstrap org.w3c.dom.events org.w3c.dom.ls org.xml.sax org.xml.sax.ext org.xml.sax.helpers

    jdk 中文版

    java jdk api帮助文档中文版 JavaTM Platform ...org.omg.stub.java.rmi org.w3c.dom org.w3c.dom.bootstrap org.w3c.dom.events org.w3c.dom.ls org.xml.sax org.xml.sax.ext org.xml.sax.helpers

    Javase-6.0_中文API_HTML(最新更新)

    javase 中文API 最新版 ******************************* ...org.omg.stub.java.rmi org.w3c.dom org.w3c.dom.bootstrap org.w3c.dom.events org.w3c.dom.ls org.xml.sax org.xml.sax.ext org.xml.sax.helpers

    java操作xml dom dom4j sax jdom

    Java 四种方式操作xml,包括xml,dom,sax,jdom这四种方式的一个简单例子。

    dom.sax.pull解析

    Ø 1、DOM(org.w3c.dom) Ø “文档对象模型”方式,解析完的Xml将生成一个树状结构的对象。 Ø 2、SAX(org.xml.sax) Ø SimpleAPI for XML,以事件的形式通知程序,对Xml进行解析。 Ø 3、XMLPULL(org.xmlpull.v1) ...

    JAVA_API1.6文档(中文)

    javax.xml.crypto.dsig.dom javax.xml.crypto.dsig 包特定于 DOM 的类。 javax.xml.crypto.dsig.keyinfo 用来解析和处理 KeyInfo 元素和结构的类。 javax.xml.crypto.dsig.spec XML 数字签名的参数类。 javax.xml...

    java解析xml

    // 把要解析的XML文档转化为输入流,以便DOM解析器解析它 InputStream is = new FileInputStream("test.xml"); // 解析XML文档的输入流,得到一个Document Document doc = dombuilder.parse(is); // 得到XML...

    Java解析XML工具类--(java源码)

    import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 本类是专门解析XML文件的,主要用于为系统读取自己的配置文件时提供最方便的解析操作 * @author HX * */ ...

    分享一个xml解析方法

    一个xml的解析方法,供参考。 import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource;

    dom4j api 参考手册

    org.dom4j.dom An implementation of the dom4j API which also supports the W3C object model. org.dom4j.dtd Classes to represent the DTD declarations. org.dom4j.io Provides input and output via SAX and ...

    JavaSE-6.0-英文手册(2008/11/30_FullUpdate)

    JDKTM 6 Documentation Legal Notices API, Language, and ...org.omg.stub.java.rmi org.w3c.dom org.w3c.dom.bootstrap org.w3c.dom.events org.w3c.dom.ls org.xml.sax org.xml.sax.ext org.xml.sax.helpers

    java dom 解析 xml 实例

    java dom 解析 xml 实例 介绍w3c中的元素的用法,以及在解析xml过程中用到的API进行详细解释

    Chenso:Chenso 是一个 org.w3c.dom XML wrapperparser 库

    Chenso 是一个 org.w3c.dom XML 包装器/解析器库。 基本用法 运行测试 视窗 gradlew test Unix ./gradlew test 建造 视窗 gradlew.bat build Unix ./gradlew build 用法 获取 XML 元素中名称的第一个值 String ...

    易语言模块 XMLDOM 解析 构造 获取 更改 添加 删除 遍历元素 格式化XML

    示例源码: ...什么是 XML DOM? XML DOM 是: 用于 XML 的标准对象模型 用于 XML 的标准编程接口 中立于平台和语言 W3C 标准 XML DOM 定义了所有 XML 元素...5、XMLDOM教程文档推荐参考:https://www.w3cschool.cn/xmldom

    [Java参考文档]

    javax.xml.crypto.dsig.dom javax.xml.crypto.dsig 包特定于 DOM 的类。 javax.xml.crypto.dsig.keyinfo 用来解析和处理 KeyInfo 元素和结构的类。 javax.xml.crypto.dsig.spec XML 数字签名的参数类。 javax.xml...

    使用dom4j解析XML

    dom4j是一种解析XML文档的开放源代码XML框架。本文介绍如何使用包含在dom4j中的解析器创建并修改...与W3C DOM API相比,使用dom4j所包含的解析器的好处是dom4j拥有本地的XPath支持。DOM解析器不支持使用XPath选择节点。

    fluentxml4j:Java中用于XML解析,序列化,XPath查询和转换的fluent API

    从java.io输入解析到org.w3c.dom.Document 将org.w3c.dom.Document序列化为任何java.io输出 通过XSLT和自定义过滤器支持将java.io,SAX,StAX,JAXB输入转换为它们中的任何一个 通过XPath查询org.w3c.dom.Document...

    JavaAPI1.6中文chm文档 part1

    javax.xml.crypto.dsig.dom javax.xml.crypto.dsig 包特定于 DOM 的类。 javax.xml.crypto.dsig.keyinfo 用来解析和处理 KeyInfo 元素和结构的类。 javax.xml.crypto.dsig.spec XML 数字签名的参数类。 javax.xml...

Global site tag (gtag.js) - Google Analytics