XML之DOM解析詳解

參考文獻: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());         }     }   }
相關文章
相關標籤/搜索