隨筆-57  評論-117  文章-1  trackbacks-0

          Dom4j也可以很方便完成XML文檔的創(chuàng)建、元素的修改、文檔的查詢遍歷等,但dom4j稍比jdom復(fù)雜一點(diǎn),不過在大片文檔的情況下dom4j的性能要不jdom好。

          # 準(zhǔn)備

          首先,提供相關(guān)的jar包

          Dom4j jar包下載:

          http://sourceforge.net/projects/dom4j/files/dom4j-2.0.0-ALPHA-2/

          jaxen jar下載:

          http://repo1.maven.org/maven2/jaxen/jaxen/1.1.1/jaxen-1.1.1.jar

          和dom4j依賴或相關(guān)的jar:

          http://dom4j.sourceforge.net/dependencies.html

          Junit-jar下載:

          http://ebr.springsource.com/repository/app/bundle/version/download?name=com.springsource.org.junit&version=4.8.1&type=binary

          其次,準(zhǔn)備測試案例的部分代碼:

          package com.hoo.test;
           
          import java.io.File;
          import java.util.Iterator;
          import java.util.List;
          import org.dom4j.Attribute;
          import org.dom4j.Document;
          import org.dom4j.DocumentException;
          import org.dom4j.DocumentHelper;
          import org.dom4j.Element;
          import org.dom4j.Node;
          import org.dom4j.QName;
          import org.dom4j.dom.DOMAttribute;
          import org.dom4j.io.SAXReader;
          import org.dom4j.tree.BaseElement;
          import org.junit.After;
          import org.junit.Before;
          import org.junit.Test;
           
          /**
           * <b>function:</b> 使用Dom4j操作XML
           * @author hoojo
           * @createDate 2011-8-5 下午06:15:40
           * @file DocumentTest.java
           * @package com.hoo.test
           * @project Dom4jTest
           * @blog http://blog.csdn.net/IBM_hoojo
           * @email hoojo_@126.com
           * @version 1.0
           */
          public class DocumentTest {
              
              private SAXReader reader = null;
              
              @Before
              public void init() {
                  reader = new SAXReader();
              }
              
              @After
              public void destory() {
                  reader = null;
                  System.gc();
              }
              
              public void fail(Object o) {
                  if (o != null)
                      System.out.println(o);
              }
          }

          # 創(chuàng)建一篇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>

          創(chuàng)建文檔代碼如下:

          /**
           * <b>function:</b>創(chuàng)建文檔
           * @author hoojo
           * @createDate 2011-8-5 下午06:18:18
           */
          @Test
          public void createDocument() {
              //創(chuàng)建一篇文檔
              Document doc = DocumentHelper.createDocument();
              
              //添加一個(gè)元素
              Element root = doc.addElement("catalog");
              //為root元素添加注釋
              root.addComment("An XML Catalog");
              //添加標(biāo)記
              root.addProcessingInstruction("target", "instruction");
              
              //創(chuàng)建元素
              Element journalEl = new BaseElement("journal");
              //添加屬性
              journalEl.addAttribute("title", "XML Zone");
              journalEl.addAttribute("publisher", "IBM developerWorks");
              root.add(journalEl);
              
              //添加元素
              Element articleEl = journalEl.addElement("article");
              articleEl.addAttribute("level", "Intermediate");
              articleEl.addAttribute("date", "December-2001");
              
              Element titleEl = articleEl.addElement("title");
              //設(shè)置文本內(nèi)容
              titleEl.setText("Java configuration with XML Schema");
              //titleEl.addText("Java configuration with XML Schema");
              
              Element authorEl = articleEl.addElement("author");
              authorEl.addElement("firstname").setText("Marcello");
              authorEl.addElement("lastname").addText("Vitaletti");
              
              //可以使用 addDocType() 方法添加文檔類型說明。 
              doc.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd"); 
           
              fail(doc.getRootElement().getName());
              
              //將xml轉(zhuǎn)換成文本
              fail(doc.asXML());
              
              //寫入到文件
              /*XMLWriter output;
              try {
                  output = new XMLWriter(new FileWriter(new File("file/catalog.xml")));
                  output.write(doc);
                  output.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }*/
          }

          * DocumentHelper是一個(gè)文檔助手類(工具類),它可以完成文檔、元素、文本、屬性、注釋、CDATA、Namespace、XPath的創(chuàng)建,以及利用XPath完成文檔的遍歷和將文本轉(zhuǎn)換成Document;

          parseText完成將xml字符串轉(zhuǎn)換成Doc的功能

          Document doc = DocumentHelper.parseText("<root></root>");

          createDocument創(chuàng)建一個(gè)文檔

          Document doc = DocumentHelper.createDocument();

          如果帶參數(shù)就會(huì)創(chuàng)建一個(gè)帶有根元素的文檔

          createElement創(chuàng)建一個(gè)元素

          Element el = DocumentHelper.createElement("el");

          * Document的addElement方法可以給當(dāng)前文檔添加一個(gè)子元素

          Element root = doc.addElement("catalog");

          * addComment方法可以添加一段注釋

          root.addComment("An XML Catalog");

          為root元素添加一段注釋

          * addProcessingInstruction添加一個(gè)標(biāo)記

          root.addProcessingInstruction("target", "instruction");

          為root元素添加一個(gè)標(biāo)記

          * new BaseElement可以創(chuàng)建一個(gè)元素

          Element journalEl = new BaseElement("journal");

          * addAttribute添加屬性

          journalEl.addAttribute("title", "XML Zone");

          * add添加一個(gè)元素

          root.add(journalEl);

          將journalEl元素添加到root元素中

           

          * addElement添加一個(gè)元素,并返回當(dāng)前元素

          Element articleEl = journalEl.addElement("article");

          給journalEl元素添加一個(gè)子元素article

          * setText、addText可以設(shè)置元素的文本

          authorEl.addElement("firstname").setText("Marcello");
          authorEl.addElement("lastname").addText("Vitaletti");

          * addDocType可以設(shè)置文檔的DOCTYPE

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

          * asXML可以將文檔或元素轉(zhuǎn)換成一段xml字符串

          doc.asXML();
          root.asXML();

          * XMLWriter類可以把文檔寫入到文件中

          output = new XMLWriter(new FileWriter(new File("file/catalog.xml")));
          output.write(doc);
          output.close();

          # 修改XML文檔內(nèi)容

          /**
           * <b>function:</b> 修改XML內(nèi)容
           * @author hoojo
           * @createDate 2011-8-9 下午03:37:04
           */
          @SuppressWarnings("unchecked")
          @Test
          public void modifyDoc() {
              try {
                  Document doc = reader.read(new File("file/catalog.xml"));
                  
                  //修改屬性內(nèi)容
                  List list = doc.selectNodes("http://article/@level");
                  Iterator<Attribute> iter = list.iterator();
                  while (iter.hasNext()) {
                      Attribute attr = iter.next();
                      fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
                      if ("Intermediate".equals(attr.getValue())) {
                          //修改屬性值
                          attr.setValue("Introductory");
                          fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
                      }
                  }
                  
                  list = doc.selectNodes("http://article/@date");
                  iter = list.iterator();
                  while (iter.hasNext()) {
                      Attribute attr = iter.next();
                      fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
                      if ("December-2001".equals(attr.getValue())) {
                          //修改屬性值
                          attr.setValue("December-2011");
                          fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
                      }
                  }
                  
                  //修改節(jié)點(diǎn)內(nèi)容
                  list = doc.selectNodes("http://article");
                  Iterator<Element> it = list.iterator();
                  while (it.hasNext()) {
                      Element el = it.next();
                      fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue());
                      //修改title元素
                      Iterator<Element> elIter = el.elementIterator("title");
                      while(elIter.hasNext()) {
                          Element titleEl = elIter.next();
                          fail(titleEl.getName() + "#" + titleEl.getText() + "#" + titleEl.getStringValue());
                          if ("Java configuration with XML Schema".equals(titleEl.getTextTrim())) {
                              //修改元素文本值
                              titleEl.setText("Modify the Java configuration with XML Schema");
                              fail(titleEl.getName() + "#" + titleEl.getText() + "#" + titleEl.getStringValue());
                          }
                      }
                  }
                  
                  //修改節(jié)點(diǎn)子元素內(nèi)容
                  list = doc.selectNodes("http://article/author");
                  it = list.iterator();
                  while (it.hasNext()) {
                      Element el = it.next();
                      fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue());
                      List<Element> childs = el.elements();
                      for (Element e : childs) {
                          fail(e.getName() + "#" + e.getText() + "#" + e.getStringValue());
                          if ("Marcello".equals(e.getTextTrim())) {
                              e.setText("Ayesha");
                          } else if ("Vitaletti".equals(e.getTextTrim())) {
                              e.setText("Malik");
                          } 
                          fail(e.getName() + "#" + e.getText() + "#" + e.getStringValue());
                      }
                  }
                  
                  //寫入到文件
                  /*XMLWriter output = new XMLWriter(new FileWriter(new File("file/catalog-modified.xml")));
                  output.write(doc);
                  output.close();*/
              } catch (DocumentException e) {
                  e.printStackTrace();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }

          * reader.read(new File("file/catalog.xml"));讀取指定xml文件內(nèi)容到文檔中;

          * selectNodes是XPath的查詢方法,完成xml文檔的查詢,傳遞xpath路徑。其使用方法可以參考jdom的xpath的使用方法:

               http://www.cnblogs.com/hoojo/archive/2011/08/11/2134638.html

          * getName獲取元素標(biāo)簽名稱、getValue、getText獲取值、文本內(nèi)容;

          * elementIterator("title");獲取當(dāng)前節(jié)點(diǎn)下所有的title元素,返回Iterator;

          * elements獲取下面所有的子元素,返回的是一個(gè)集合List;

           

          # 顯示文檔相關(guān)信息

          private String format(int i) {
              String temp = "";
              while (i > 0) {
                  temp += "--";
                  i--;
              }
              return temp;
          }
           
          /**
           * <b>function:</b>遞歸顯示文檔內(nèi)容
           * @author hoojo
           * @createDate 2011-8-9 下午03:43:45
           * @param i
           * @param els
           */
          private void print(int i, List<Element> els) {
              i++;
              for (Element el : els) {
                  fail(format(i) + "##" + el.getName() + "#" + el.getTextTrim());
                  if (el.hasContent()) {
                      print(i, el.elements());
                  } 
              }
          }
           
          /**
           * <b>function:</b>顯示文檔相關(guān)信息
           * @author hoojo
           * @createDate 2011-8-9 下午03:44:10
           */
          @Test
          public void printInfo() {
              try {
                  Document doc = reader.read(new File("file/catalog.xml"));
                  fail("asXML: " + doc.asXML());
                  
                  fail(doc.asXPathResult(new BaseElement("article")));
                  List<Node> list = doc.content();
                  for (Node node : list) {
                      fail("Node: " + node.getName() + "#" + node.getText() + "#" + node.getStringValue());
                  }
                  
                  fail("-----------------------------");
                  print(0, doc.getRootElement().elements());
                  
                  fail("getDocType: " + doc.getDocType());
                  fail("getNodeTypeName: " + doc.getNodeTypeName());
                  fail("getPath: " + doc.getRootElement().getPath());
                  fail("getPath: " + doc.getRootElement().getPath(new BaseElement("journal")));
                  fail("getUniquePath: " + doc.getRootElement().getUniquePath());
                  fail("getXMLEncoding: " + doc.getXMLEncoding());
                  fail("hasContent: " + doc.hasContent());
                  fail("isReadOnly: " + doc.isReadOnly());
                  fail("nodeCount: " + doc.nodeCount());
                  fail("supportsParent: " + doc.supportsParent());
              } catch (DocumentException e) {
                  e.printStackTrace();
              }
              fail("getEncoding: " + reader.getEncoding());
              fail("isIgnoreComments: " + reader.isIgnoreComments());
              fail("isMergeAdjacentText: " + reader.isMergeAdjacentText());
              fail("isStringInternEnabled: " + reader.isStringInternEnabled());
              fail("isStripWhitespaceText: " + reader.isStripWhitespaceText());
              fail("isValidating: " + reader.isValidating());
          }

          # 刪除文檔內(nèi)容

          /**
           * <b>function:</b> 刪除節(jié)點(diǎn)內(nèi)容
           * @author hoojo
           * @createDate 2011-8-9 下午03:47:44
           */
          @Test
          public void removeNode() {
              try {
                  Document doc = reader.read(new File("file/catalog-modified.xml"));
                  fail("comment: " + doc.selectSingleNode("http://comment()"));
                  //刪除注釋
                  doc.getRootElement().remove(doc.selectSingleNode("http://comment()"));
                  
                  Element node = (Element) doc.selectSingleNode("http://article");
                  //刪除屬性
                  node.remove(new DOMAttribute(QName.get("level"), "Introductory"));
                  //刪除元素 節(jié)點(diǎn)
                  node.remove(doc.selectSingleNode("http://title"));
                  
                  //只能刪除下一級節(jié)點(diǎn),不能超過一級;(需要在父元素的節(jié)點(diǎn)上刪除子元素)
                  Node lastNameNode = node.selectSingleNode("http://lastname");
                  lastNameNode.getParent().remove(lastNameNode);
                  
                  fail("Text: " + doc.selectObject("http://*[text()='Ayesha']"));
                  Element firstNameEl = (Element)doc.selectObject("http://firstname");
                  fail("Text: " + firstNameEl.selectSingleNode("text()"));
                  
                  //刪除text文本
                  //firstNameEl.remove(firstNameEl.selectSingleNode("text()"));
                  //firstNameEl.remove(doc.selectSingleNode("http://firstname/text()"));
                  firstNameEl.remove(doc.selectSingleNode("http://*[text()='Ayesha']/text()"));
                  
                  //刪除子元素author
                  //node.remove(node.selectSingleNode("http://author"));
                  
                  fail(doc.asXML());
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }

          * 刪除注釋

          doc.getRootElement().remove(doc.selectSingleNode("http://comment()"));

          刪除root元素下面的注釋

          * 刪除屬性

          node.remove(new DOMAttribute(QName.get("level"), "Introductory"));

          刪除node節(jié)點(diǎn)中的名稱為level,其值為Introductory的屬性

          * 刪除元素

          node.remove(doc.selectSingleNode("http://title"));

          刪除node節(jié)點(diǎn)下的title元素

          * 刪除文本

          firstNameEl.remove(firstNameEl.selectSingleNode("text()"));
          firstNameEl.remove(doc.selectSingleNode("http://firstname/text()"));
          firstNameEl.remove(doc.selectSingleNode("http://*[text()='Ayesha']/text()"));

          刪除firstNameEl的文本內(nèi)容



          作者:hoojo
          出處:
          blog:http://blog.csdn.net/IBM_hoojo
                   http://hoojo.cnblogs.com
          本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責(zé)任的權(quán)利。


          版權(quán)所有,轉(zhuǎn)載請注明出處 本文出自:
          分享道版權(quán)所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明出處,謝謝
          posted on 2011-08-11 15:52 hoojo 閱讀(3240) 評論(0)  編輯  收藏 所屬分類: JavaEEJavaSEJSON&XML
          主站蜘蛛池模板: 白水县| 青海省| 靖远县| 丹巴县| 藁城市| 延川县| 靖宇县| 迁安市| 大同市| 临武县| 铁岭县| 衡山县| 类乌齐县| 彰化市| 承德市| 芜湖市| 仙游县| 晴隆县| 枣阳市| 桐城市| 阜康市| 工布江达县| 吴堡县| 儋州市| 黄石市| 扎赉特旗| 崇义县| 新乐市| 鄄城县| 屯门区| 宣汉县| 绥化市| 靖远县| 高雄县| 璧山县| 河池市| 乌鲁木齐县| 新龙县| 五家渠市| 望奎县| 临安市|