posts - 22, comments - 32, trackbacks - 0, articles - 73
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          Java DOM 解析 XML詳解

          Posted on 2010-03-02 15:04 為自己代言 閱讀(20897) 評論(2)  編輯  收藏
           

          DOM解析器的接口已經被W3C標準化了。org.w3.dom包包含了接口類型的定義,比如:

          DocumentElement等。不同的提供者,比如Apache OrganizationIBM都編寫了實現這些接口的DOM解析器。SUN公司的XML處理JAVA APIJava 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:通過文件方式讀?。?/span>

          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 流的讀?。?/span>

                 FileInputStream inputstream = new FileInputStream(

                            "F:""employees.xml");

              Document doc=builder.parse(inputstream);

          這里就寫這么多了,在詳細的請自己去查查閱資料。

          下邊是employees.xml 這個XML文件的內容:

              <?xml version="1.0" encoding="GBK"?>

          <employees>

          <employee email="zzzlyr@163.com">

          <name>李明</name>

          <sex>女孩子</sex>

          <age>30</age>

          </employee>

          <employee email="zzzlyr112@163.com">

          <name>張釗釗</name>

          <sex></sex>

          <age>28</age>

          </employee>

          </employees>

          publicvoid parseXml(String fileName) {

                 try {

                     DocumentBuilderFactory factory = DocumentBuilderFactory

                            .newInstance();

                     DocumentBuilder builder = factory.newDocumentBuilder();

                     Document document = builder.parse(fileName);

                     // 1.獲得文檔根元素對對象;

                     Element root = document.getDocumentElement();

                     // 獲得文檔根元素下一級子元素所有元素;

                     NodeList nodeList = root.getChildNodes();

                     System.out.println(root.getNodeName());

                     if (null != root) {

                        for (int i = 0; i < nodeList.getLength(); i++) {

                            Node child = nodeList.item(i);

                            // 輸出child的屬性;

                            System.out.println(child);

                           

          //                if (child.getNodeType() == Node.ELEMENT_NODE) {

          //                   System.out.println(child.getAttributes().getNamedItem(

          //                          "email").getNodeValue());

          //                }

          //

          //                for (Node node = child.getFirstChild(); node != null; node = node

          //                       .getNextSibling()) {

          //

          //                   if (node.getNodeType() == Node.ELEMENT_NODE) {

          //                       if ("name".equals(node.getNodeName())) {

          //                          System.out.println(node.getFirstChild()

          //                                 .getNodeValue());

          //                       }

          //                   }

          //                   if (node.getNodeType() == Node.ELEMENT_NODE) {

          //                       if ("sex".equals(node.getNodeName())) {

          //                           System.out.println(node.getFirstChild()

          //                                 .getNodeValue());

          //                       }

          //                   }

          //                   if (node.getNodeType() == Node.ELEMENT_NODE) {

          //                       if ("age".equals(node.getNodeName())) {

          //                          System.out.println(node.getFirstChild()

          //                                 .getNodeValue());

          //                       }

          //                   }

          //                }

                        }

                     }

                 } catch (ParserConfigurationException e) {

                     e.printStackTrace();

                 } catch (IOException e) {

                     e.printStackTrace();

                 } catch (SAXException e) {

                     e.printStackTrace();

                 }

              }

          我為了研究解析過程把寫好的代碼注釋掉了,看這層輸出結果:

          employees

          [#text:

          ]

          [employee: null]

          [#text:

          ]

          [employee: null]

          [#text:

          ]

          第一個是整個文檔的根元素名稱,下邊結果是第一層for輸出結果,從結果可見而知

          遍歷了整個XML文件的所有子元素進行輸出,如果不清楚可以和原XML文件對比可知

          去掉注釋部分結果如下:

          employees

          zzzlyr@163.com

          李明

          女孩子

          30

          zzzlyr112@163.com

          張釗釗

          28

          從結果可知,DOM解析過程是先解析整個XML文件所有子元素,然后在能過第二個for

          解析子元素下的子元素;

          但是為什么第一個有類似于這樣東西[#text:] 這是查了半天資料,原因是XML 文件元素之間的空白字符也是一個元素,<employees></employees>這之間空白;

          child.getNodeType() == Node.ELEMENT_NODE代碼可以忽略掉類似于這樣東西;

          這是解析,還有創建XML文檔,自己看代碼吧,我不多解釋了;

          整個代碼:

          package com.junhai.xml.test;

          import java.io.FileNotFoundException;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.PrintWriter;

          import javax.xml.parsers.DocumentBuilder;
          import javax.xml.parsers.DocumentBuilderFactory;
          import javax.xml.parsers.ParserConfigurationException;
          import javax.xml.transform.OutputKeys;
          import javax.xml.transform.Transformer;
          import javax.xml.transform.TransformerConfigurationException;
          import javax.xml.transform.TransformerException;
          import javax.xml.transform.TransformerFactory;
          import javax.xml.transform.dom.DOMSource;
          import javax.xml.transform.stream.StreamResult;

          import org.w3c.dom.Attr;
          import org.w3c.dom.Document;
          import org.w3c.dom.Element;
          import org.w3c.dom.Node;
          import org.w3c.dom.NodeList;
          import org.xml.sax.SAXException;

          import com.sun.org.apache.xerces.internal.util.XMLDocumentFilterImpl;

          public class DomXmlDemo extends XMLDocumentFilterImpl implements XmlDocument {
           private Document document;

           public void init() {
            try {
             DocumentBuilderFactory factory = DocumentBuilderFactory
               .newInstance();
             DocumentBuilder builder = factory.newDocumentBuilder();
             this.document = builder.newDocument();

            } catch (ParserConfigurationException e) {
             System.out.println(e.getMessage());
            }
           }

           public void createXml(String fileName) {
            this.init();
            // 創建XML文件根節點;
            Element root = this.document.createElement("employees");
            this.document.appendChild(root);
            // 創建XML文件根節點子節點;
            Element employee = this.document.createElement("employee");
            // 向根節點添加屬性節點;
            Attr email = this.document.createAttribute("email");
            email.setNodeValue("zzzlyr@163.com");
            // 把屬性節點對象,追加到達根節點上去;
            employee.setAttributeNode(email);

            Element name = this.document.createElement("name");
            // 向XML文件根節點子節點追加數據;
            name.appendChild(this.document.createTextNode("李明"));

            // 在把子節點的屬性追加到子節點中元素中去;
            employee.appendChild(name);

            Element sex = this.document.createElement("sex");
            sex.appendChild(this.document.createTextNode("女孩子"));
            employee.appendChild(sex);

            Element age = this.document.createElement("age");
            age.appendChild(this.document.createTextNode("30"));
            employee.appendChild(age);
            root.appendChild(employee);

            
           
            // 創建XML文件根節點子節點;
            Element employee2 = this.document.createElement("employee");
            // 向根節點添加屬性節點;
            Attr email2 = this.document.createAttribute("email");
            email2.setNodeValue("zzzlyr2@163.com");
            // 把屬性節點對象,追加到達根節點上去;
            employee2.setAttributeNode(email2);
            Element name2 = this.document.createElement("name");
            // 向XML文件根節點子節點追加數據;
            name2.appendChild(this.document.createTextNode("張釗釗"));

            // 在把子節點的屬性追加到子節點中元素中去;
            employee2.appendChild(name2);

            Element sex2 = this.document.createElement("sex");
            sex2.appendChild(this.document.createTextNode("男"));
            employee2.appendChild(sex2);

            Element age2 = this.document.createElement("age");
            age2.appendChild(this.document.createTextNode("28"));
            employee2.appendChild(age2);
            root.appendChild(employee2);
            
            
            
            
            
            TransformerFactory tf = TransformerFactory.newInstance();
            try {
             Transformer transformer = tf.newTransformer();
             // Transformer transformer1=tf.newTransformer(Source source);
             DOMSource source = new DOMSource(document);
             transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
             try {
              PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
              StreamResult result = new StreamResult(pw);
              transformer.transform(source, result);
              System.out.println("生成XML文件成功!");

             } catch (FileNotFoundException e) {
              e.printStackTrace();
              System.out.println("文件沒有找到!");
             } catch (TransformerException e) {
              e.printStackTrace();
              System.out.println("生成XML文件失敗!");
             }

            } catch (TransformerConfigurationException e) {
             e.printStackTrace();
            }

           }

           public void parseXml(String fileName) {
            try {
             DocumentBuilderFactory factory = DocumentBuilderFactory
               .newInstance();
             DocumentBuilder builder = factory.newDocumentBuilder();
             Document document = builder.parse(fileName);
             // 1.獲得文檔根元素對對象;
             Element root = document.getDocumentElement();
             // 獲得文檔根元素下一級子元素所有元素;
             NodeList nodeList = root.getChildNodes();
             System.out.println(root.getNodeName());
             if (null != root) {
              for (int i = 0; i < nodeList.getLength(); i++) {
               Node child = nodeList.item(i);
               // 輸出child的屬性;
               //System.out.println(child);
               
               if (child.getNodeType() == Node.ELEMENT_NODE) {
                System.out.println(child.getAttributes().getNamedItem(
                  "email").getNodeValue());
               }

               for (Node node = child.getFirstChild(); node != null; node = node
                 .getNextSibling()) {

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                 if ("name".equals(node.getNodeName())) {
                  System.out.println(node.getFirstChild()
                    .getNodeValue());
                 }
                }
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                 if ("sex".equals(node.getNodeName())) {
                  System.out.println(node.getFirstChild()
                    .getNodeValue());
                 }
                }
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                 if ("age".equals(node.getNodeName())) {
                  System.out.println(node.getFirstChild()
                    .getNodeValue());
                 }
                }
               }
              }
             }

            } catch (ParserConfigurationException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            } catch (SAXException e) {
             e.printStackTrace();
            }

           }

           public static void main(String[] args) {
            DomXmlDemo dom = new DomXmlDemo();
             dom.createXml("F:\\employees.xml");
            dom.parseXml("F:\\employees.xml");
           }
          }





          結果如下:

          生成XML文件成功!
          employees
          zzzlyr@163.com
          李明
          女孩子
          30
          zzzlyr2@163.com
          張釗釗



          評論

          # re: Java DOM 解析 XML詳解[未登錄]  回復  更多評論   

          2015-04-21 16:29 by 1
          1

          # re: Java DOM 解析 XML詳解  回復  更多評論   

          2015-09-20 00:57 by szm
          Great!

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 英德市| 墨竹工卡县| 正阳县| 永登县| 安徽省| 东平县| 南岸区| 永仁县| 夹江县| 崇左市| 邵阳县| 安福县| 淳安县| 黄骅市| 四子王旗| 健康| 普宁市| 文安县| 巴东县| 昌图县| 永福县| 成安县| 郑州市| 商南县| 文化| 锡林浩特市| 永福县| 花莲县| 金山区| 盐亭县| 沐川县| 东莞市| 囊谦县| 山西省| 冀州市| 乳源| 墨竹工卡县| 福海县| 皋兰县| 汉寿县| 扬中市|