加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML之DOM解析详解

发布时间:2020-12-16 05:57:18 所属栏目:百科 来源:网络整理
导读:参考文献:http://www.blogjava.net/zzzlyr/articles/314288.html xmljava的解析方式有很多种,我们现在就先看一下关于XML解析中的DOM解析 DOM解析器的接口已经被W3C标准化了。org.w3.dom包包含了接口类型的定义,比如: Document和Element等。不同的提供者,
参考文献:http://www.blogjava.net/zzzlyr/articles/314288.html


xmljava的解析方式有很多种,我们现在就先看一下关于XML解析中的DOM解析


DOM解析器的接口已经被W3C标准化了。org.w3.dom包包含了接口类型的定义,比如:


Document和Element等。不同的提供者,比如Apache Organization和IBM都编写了实现这些接口的DOM解析器。SUN公司的XML处理JAVA API(Java API for XML Processing,JAXP)


库实际上可以插入到这些解析器中的任意一个中。但是SUN公司也在JAVA SDK中包含了自己的DOM解析器。在本文中我使用的就是JAVA的解析器。


1:要读入一个XML文档,首先要一个DocumentBuilder对象,可以这样得到:


DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();


DocumentBuilder builder = factory.newDocumentBuilder();


2:现在可以从文件中去读取一个XML文件了(文件路径:"F:""employees.xml")


得到XML文件有三种方式:


1:通过文件方式读取:


File file=new File("F:""employees.xml");


Document doc=builder.parse(file);


2:通过一个URL方式读取:


URL u=new URL("http://java.sun.com/index.html")


Document doc=builder.parse(u);


3:可以能过java IO 流的读取:


FileInputStream inputstream = new FileInputStream(


"F:""employees.xml");


Document doc=builder.parse(inputstream);


好了,有了基本的了解后,我们开始上代码:




<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
   <NO>A1234</NO>
   <ADDR>四川省XX县XX镇XX路X段XX号</ADDR>
</VALUE>
<VALUE>
  <NO>B1234</NO>
   <ADDR>四川省XX市XX乡XX村XX组</ADDR>
</VALUE>
</RESULT>
然后是解析代码:


package www.yq.com.src;

import java.io.File;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
* @Project XMLSimpleTest
* @File MyTest.java
* @Package www.yq.com.src
* @Date 2016年1月25日 下午3:41:39
* @Author * @email */ public class MyTest { //DOM(JAXP Crimson解析器) public static void main(String[] args) throws ParserConfigurationException,SAXException,IOException { File f = new File("E:qi.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); Document document = documentBuilder.parse(f); NodeList nodeList = document.getElementsByTagName("VALUE"); for (int i = 0; i < nodeList.getLength(); i++) { System.out.println("车牌号:"+document.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue()); System.out.println("车牌地址:"+document.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue()); } } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读