Dom4j java編程__編程

來源:互聯網
上載者:User

dom4j 是一種解析 XML 文檔的開放原始碼 XML 架構。本文介紹如何使用包含在 dom4j 中的解析器建立並修改 XML 文檔。 

dom4j API 包含一個解析 XML 文檔的工具。本文中將使用這個解析器建立一個樣本 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。 

 <?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>

與 W3C DOM API 相比,使用 dom4j 所包含的解析器的好處是 dom4j 擁有本地的 XPath 支援。DOM 解析器不支援使用 XPath 選擇節點。 

本文包括以下幾個部分: 

•預先設定 
•建立文檔 
•修改文檔 

預先設定 

這個解析器可以從 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 java.io.*; import java.util.regex.*; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

使用 DocumentHelper 類建立一個文檔執行個體。 DocumentHelper 是產生 XML 文檔節點的 dom4j API 工廠類。 Java代碼  Document document = DocumentHelper.createDocument();   




使用 addElement() 方法建立根項目 catalog 。 addElement() 用於向 XML 文檔中增加元素。 Java代碼  Element catalogElement = document.addElement("catalog");   




在 catalog 元素中使用 addComment() 方法添加註釋“An XML catalog”。  Java代碼  catalogElement.addComment("An XML catalog");  




在 catalog 元素中使用 addProcessingInstruction() 方法增加一個處理指示。 Java代碼  catalogElement.addProcessingInstruction("target","text");   




在 catalog 元素中使用 addElement() 方法增加 journal 元素。 Java代碼  Element journalElement =  catalogElement.addElement("journal");   




使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 屬性。 Java代碼  journalElement.addAttribute("title", "XML Zone");            journalElement.addAttribute("publisher", "IBM developerWorks");   




向 article 元素中添加 journal 元素。 Java代碼  Element articleElement=journalElement.addElement("article");   




為 article 元素增加 level 和 date 屬性。 Java代碼  articleElement.addAttribute("level", "Intermediate");         articleElement.addAttribute("date", "December-2001");   




向 article 元素中增加 title 元素。 Java代碼  Element titleElement=articleElement.addElement("title");  




使用 setText() 方法設定 article 元素的文本。 Java代碼  titleElement.setText("Java configuration with XML Schema");  




在 article 元素中增加 author 元素。  Java代碼  Element authorElement=articleElement.addElement("author");   




在 author 元素中增加 firstname 元素並設定該元素的文本。 Java代碼  Element  firstNameElement=authorElement.addElement("firstname");        firstNameElement.setText("Marcello");   




在 author 元素中增加 lastname 元素並設定該元素的文本。 Java代碼  Element lastNameElement=authorElement.addElement("lastname");        lastNameElement.setText("Vitaletti");   




可以使用 addDocType() 方法添加文件類型說明。 Java代碼  document.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd");   




這樣就向 XML 文檔中增加文件類型說明: Java代碼  <!DOCTYPE catalog SYSTEM "file://c:/Dtds/catalog.dtd">   

 


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

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

所示的例子程式 XmlDom4J.java 用於建立 XML 文檔 catalog.xml 

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(); }} 

  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("//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("//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 文檔。 

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("//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("//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("//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("//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("//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 文檔。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.