寧靜的Thinking

          認真工作,及時總結
          隨筆 - 3, 文章 - 0, 評論 - 0, 引用 - 0

          導航

          <2012年10月>
          30123456
          78910111213
          14151617181920
          21222324252627
          28293031123
          45678910

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          Dom4j使用入門—xml的解析

          轉載:http://www.ibm.com/developerworks/cn/xml/x-dom4j.html 

          dom4j API 包含一個解析 XML 文檔的工具。本文中將使用這個解析器創建一個示例 XML 文檔。清單 1 顯示了這個示例 XML 文檔,catalog.xml。

          清單 1. 示例 XML 文檔(catalog.xml)

          <?xml version="1.0" encoding="UTF-8"?> 
          <catalog> 
          <!--An XML Catalog--> 
          <?target instruction?>
            <journal title="XML Zone" 
                            publisher="IBM developerWorks"> 
          <article level="Intermediate" date="December-2001">
           <title>Java configuration with XML Schema</title> 
           <author> 
               <firstname>Marcello</firstname> 
               <lastname>Vitaletti</lastname> 
           </author>
            </article>
            </journal> 
          </catalog>

          然后使用同一個解析器修改 catalog.xml,清單 2 是修改后的 XML 文檔,catalog-modified.xml。

          清單 2. 修改后的 XML 文檔(catalog-modified.xml)

          <?xml version="1.0" encoding="UTF-8"?> 
          <catalog> 
          <!--An XML catalog--> 
          <?target instruction?>
            <journal title="XML Zone"
                             publisher="IBM developerWorks"> 
          <article level="Introductory" date="October-2002">
           <title>Create flexible and extensible XML schemas</title> 
           <author> 
               <firstname>Ayesha</firstname> 
               <lastname>Malik</lastname> 
           </author> 
            </article>
            </journal> 
          </catalog>

          本文包括以下幾個部分:

          • 預先設置
          • 創建文檔
          • 修改文檔

          預先設置

          這個解析器可以從 http://dom4j.org 獲取。通過設置使 dom4j-1.4/dom4j-full.jar 能夠在 classpath 中訪問,該文件中包括 dom4j 類、XPath 引擎以及 SAX 和 DOM 接口。如果已經使用了 JAXP 解析器中包含的 SAX 和 DOM 接口,向 classpath 中增加 dom4j-1.4/dom4j.jar 。 dom4j.jar 包括 dom4j 類和 XPath 引擎,但是不含 SAX 與 DOM 接口。

          回頁首

          創建文檔

          本節討論使用 dom4j API 創建 XML 文檔的過程,并創建示例 XML 文檔 catalog.xml。

          使用 import 語句導入 dom4j API 類:

          import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; 

          使用 DocumentHelper 類創建一個文檔實例。 DocumentHelper 是生成 XML 文檔節點的 dom4j API 工廠類。

           Document document = DocumentHelper.createDocument();

          使用 addElement() 方法創建根元素 catalog 。 addElement() 用于向 XML 文檔中增加元素。

          Element catalogElement = document.addElement("catalog");

          在 catalog 元素中使用 addComment() 方法添加注釋“An XML catalog”。

           catalogElement.addComment("An XML catalog");

          在 catalog 元素中使用 addProcessingInstruction() 方法增加一個處理指令。

          catalogElement.addProcessingInstruction("target","text");

          在 catalog 元素中使用 addElement() 方法增加 journal 元素。

          Element journalElement = catalogElement.addElement("journal");

          使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 屬性。


          journalElement.addAttribute("title", "XML Zone");
                   journalElement.addAttribute("publisher", "IBM developerWorks");

          向 article 元素中添加 journal 元素。

          Element articleElement=journalElement.addElement("article");

          為 article 元素增加 level 和 date 屬性。

          articleElement.addAttribute("level", "Intermediate");
                articleElement.addAttribute("date", "December-2001");

          向 article 元素中增加 title 元素。

          Element titleElement=articleElement.addElement("title");

          使用 setText() 方法設置 article 元素的文本。

          titleElement.setText("Java configuration with XML Schema");

          在 article 元素中增加 author 元素。

          Element authorElement=articleElement.addElement("author");

          在 author 元素中增加 firstname 元素并設置該元素的文本。


          Element  firstNameElement=authorElement.addElement("firstname");
               firstNameElement.setText("Marcello");

          在 author 元素中增加 lastname 元素并設置該元素的文本。

          Element lastNameElement=authorElement.addElement("lastname"); lastNameElement.setText("Vitaletti");

          可以使用 addDocType() 方法添加文檔類型說明。

          document.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd");

          這樣就向 XML 文檔中增加文檔類型說明:

          <!DOCTYPE catalog SYSTEM "file://c:/Dtds/catalog.dtd">

          如果文檔要使用文檔類型定義(DTD)文檔驗證則必須有 Doctype。

          XML 聲明 <?xml version="1.0" encoding="UTF-8"?> 自動添加到 XML 文檔中。

          清單 3 所示的例子程序 XmlDom4J.java 用于創建 XML 文檔 catalog.xml。

          清單 3. 生成 XML 文檔 catalog.xml 的程序(XmlDom4J.java)

          import org.dom4j.Document;
          import org.dom4j.DocumentHelper;
          import org.dom4j.Element;
          import org.dom4j.io.XMLWriter;
          import java.io.*;
          public class XmlDom4J{
          public void generateDocument(){
          Document document = DocumentHelper.createDocument();
               Element catalogElement = document.addElement("catalog");
               catalogElement.addComment("An XML Catalog");
               catalogElement.addProcessingInstruction("target","text");
               Element journalElement =  catalogElement.addElement("journal");
               journalElement.addAttribute("title", "XML Zone");
               journalElement.addAttribute("publisher", "IBM developerWorks");
               Element articleElement=journalElement.addElement("article");
               articleElement.addAttribute("level", "Intermediate");
               articleElement.addAttribute("date", "December-2001");
               Element  titleElement=articleElement.addElement("title");
               titleElement.setText("Java configuration with XML Schema");
               Element authorElement=articleElement.addElement("author");
               Element  firstNameElement=authorElement.addElement("firstname");
               firstNameElement.setText("Marcello");
               Element lastNameElement=authorElement.addElement("lastname");
               lastNameElement.setText("Vitaletti");
               document.addDocType("catalog",
                                     null,"file://c:/Dtds/catalog.dtd");
              try{
              XMLWriter output = new XMLWriter(
                      new FileWriter( new File("c:/catalog/catalog.xml") ));
                  output.write( document );
                  output.close();
                  }
               catch(IOException e){System.out.println(e.getMessage());}
          }
          public static void main(String[] argv){
          XmlDom4J dom4j=new XmlDom4J();
          dom4j.generateDocument();
          }}


          這一節討論了創建 XML 文檔的過程,下一節將介紹使用 dom4j API 修改這里創建的 XML 文檔。

          回頁首

          修改文檔

          這一節說明如何使用 dom4j API 修改示例 XML 文檔 catalog.xml。

          使用 SAXReader 解析 XML 文檔 catalog.xml:

          SAXReader saxReader = new SAXReader(); Document document = saxReader.read(inputXml);

          SAXReader 包含在 org.dom4j.io 包中。

          inputXml 是從 c:/catalog/catalog.xml 創建的 java.io.File。使用 XPath 表達式從 article 元素中獲得 level 節點列表。如果 level 屬性值是“Intermediate”則改為“Introductory”。


          List list = document.selectNodes("http://article/@level" );
                Iterator iter=list.iterator();
                  while(iter.hasNext()){
                      Attribute attribute=(Attribute)iter.next();
                         if(attribute.getValue().equals("Intermediate"))
                         attribute.setValue("Introductory"); 
                 }

          獲取 article 元素列表,從 article 元素中的 title 元素得到一個迭代器,并修改 title 元素的文本。

          list = document.selectNodes("http://article" );
               iter=list.iterator();
             while(iter.hasNext()){
                 Element element=(Element)iter.next();
                Iterator iterator=element.elementIterator("title");
             while(iterator.hasNext()){
             Element titleElement=(Element)iterator.next();
             if(titleElement.getText().equals("Java configuration with XML Schema"))
               titleElement.setText("Create flexible and extensible XML schema");
              }}

          通過和 title 元素類似的過程修改 author 元素。

          清單 4 所示的示例程序 Dom4JParser.java 用于把 catalog.xml 文檔修改成 catalog-modified.xml 文檔。

          清單 4. 用于修改 catalog.xml 的程序(Dom4Jparser.java)


          import org.dom4j.Document;
          import org.dom4j.Element;
          import org.dom4j.Attribute;
          import java.util.List;
          import java.util.Iterator;
          import org.dom4j.io.XMLWriter;
          import java.io.*;
          import org.dom4j.DocumentException;
          import org.dom4j.io.SAXReader; 
          public class Dom4JParser{
           public void modifyDocument(File inputXml){
            try{
             SAXReader saxReader = new SAXReader();
             Document document = saxReader.read(inputXml);
             List list = document.selectNodes("http://article/@level" );
             Iterator iter=list.iterator();
             while(iter.hasNext()){
              Attribute attribute=(Attribute)iter.next();
              if(attribute.getValue().equals("Intermediate"))
                attribute.setValue("Introductory"); 
                 }
             
             list = document.selectNodes("http://article/@date" );
             iter=list.iterator();
             while(iter.hasNext()){
              Attribute attribute=(Attribute)iter.next();
              if(attribute.getValue().equals("December-2001"))
                attribute.setValue("October-2002");
                 }
             list = document.selectNodes("http://article" );
             iter=list.iterator();
             while(iter.hasNext()){
              Element element=(Element)iter.next();
              Iterator iterator=element.elementIterator("title");
                while(iterator.hasNext()){
                  Element titleElement=(Element)iterator.next();
                  if(titleElement.getText().equals("Java configuration with XML
                Schema"))
                  titleElement.setText("Create flexible and extensible XML schema");
                                                    }
                                          }
              list = document.selectNodes("http://article/author" );
              iter=list.iterator();
               while(iter.hasNext()){
               Element element=(Element)iter.next();
               Iterator iterator=element.elementIterator("firstname");
               while(iterator.hasNext()){
                Element firstNameElement=(Element)iterator.next();
                if(firstNameElement.getText().equals("Marcello"))
                firstNameElement.setText("Ayesha");
                                               }
                                        }
              list = document.selectNodes("http://article/author" );
              iter=list.iterator();
               while(iter.hasNext()){
                Element element=(Element)iter.next();
                Iterator iterator=element.elementIterator("lastname");
               while(iterator.hasNext()){
                Element lastNameElement=(Element)iterator.next();
                if(lastNameElement.getText().equals("Vitaletti"))
                lastNameElement.setText("Malik");
                                            }
                                         }
               XMLWriter output = new XMLWriter(
                new FileWriter( new File("c:/catalog/catalog-modified.xml") ));
               output.write( document );
               output.close();
             }
           
            catch(DocumentException e)
                           {
                            System.out.println(e.getMessage());
                                      }
            catch(IOException e){
                                 System.out.println(e.getMessage());
                              }
           }
           public static void main(String[] argv){
            Dom4JParser dom4jParser=new Dom4JParser();
            dom4jParser.modifyDocument(new File("c:/catalog/catalog.xml"));
                                                  }
             }


          這一節說明了如何使用 dom4j 中的解析器修改示例 XML 文檔。這個解析器不使用 DTD 或者模式驗證 XML 文檔。如果 XML 文檔需要驗證,可以解釋用 dom4j 與 JAXP SAX 解析器。

          回頁首

          結束語

          包含在 dom4j 中的解析器是一種用于解析 XML 文檔的非驗證性工具,可以與JAXP、Crimson 或 Xerces 集成。本文說明了如何使用該解析器創建和修改 XML 文檔。

          posted on 2012-10-18 18:25 orangle_lzz 閱讀(183) 評論(0)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 威宁| 三河市| 友谊县| 沁水县| 中阳县| 临桂县| 拉萨市| 安新县| 德钦县| 新河县| 北票市| 新泰市| 社旗县| 菏泽市| 临邑县| 宜宾县| 尉氏县| 永兴县| 莱芜市| 赞皇县| 五峰| 那曲县| 辰溪县| 赤峰市| 循化| 吴堡县| 贵阳市| 商水县| 凤城市| 南岸区| 东丽区| 新昌县| 理塘县| 河北区| 建宁县| 洪湖市| 固始县| 康定县| 铜川市| 乌什县| 靖宇县|