Chinaunix首页 | 论坛 | 博客
  • 博客访问: 499696
  • 博文数量: 109
  • 博客积分: 2331
  • 博客等级: 大尉
  • 技术积分: 1062
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-24 21:36
文章分类

全部博文(109)

文章存档

2015年(2)

2013年(1)

2012年(78)

2011年(28)

我的朋友

分类: 系统运维

2012-01-15 11:57:43

当然,首先要把dom4j.jar加入库文件
  1. package xml;

  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import org.dom4j.Attribute;
  7. import org.dom4j.Document;
  8. import org.dom4j.DocumentHelper;
  9. import org.dom4j.Element;
  10. import org.dom4j.io.OutputFormat;
  11. import org.dom4j.io.SAXReader;
  12. import org.dom4j.io.XMLWriter;


  13. /**
  14. *
  15. * @author estcele
  16. */
  17. public class Dom4jDemo {
  18.     
  19.     /** Creates a new instance of Dom4jDemo */
  20.     public Dom4jDemo() {
  21.     }
  22.     /**
  23.      *The method createXML
  24.      *建立一个XML文档,文档名由输入属性决定
  25.      *@param filename 需建立的文件名
  26.      *@return 返回操作结果
  27.      */
  28.     public boolean createXML(String fileName){
  29.         boolean isOk = false;
  30.         //建立document对象
  31.         Document doc = DocumentHelper.createDocument();
  32.         //建立XML文档的根books
  33.         Element books = doc.addElement("books");
  34.         books.addComment("This is a test for dom4j");//加入一行注释
  35.         Element book = books.addElement("book");//加入第一个book节点
  36.         book.addAttribute("show", "yes");//加入show属性内容
  37.         Element title = book.addElement("title");//加入title节点
  38.         title.setText("Dom4j Tutorials");//为title设置内容
  39.         /**加入第二个book节点*/
  40.         book = books.addElement("book");
  41.         book.addAttribute("show", "yes");
  42.         title = book.addElement("title");
  43.         title.setText("Lucene Studing");
  44.         /**加入第三个book节点*/
  45.         book = books.addElement("book");
  46.         book.addAttribute("show", "no");
  47.         title = book.addElement("title");
  48.         title.setText("Lucene in Action");
  49.         /**加入owner节点*/
  50.         Element owner = books.addElement("owner");
  51.         owner.setText("O'Reilly");
  52.         /**
  53.          *将doc中的内容写入xml文件中
  54.          **/
  55.         try{
  56.             FileWriter file = new FileWriter(new File(fileName));
  57.             XMLWriter writer = new XMLWriter(file);
  58.             writer.write(doc);
  59.             writer.close();
  60.             isOk = true;
  61.         }catch(Exception e){
  62.             e.printStackTrace();
  63.         }
  64.         return isOk;
  65.     }
  66.    /**
  67.      *the method modifigXML
  68.      * 如果book节点中show属性的内容为yes,则修改成no
  69.      * 把owner项内容改为Tshinghua,并添加date节点
  70.      * 若title内容为Dom4j Tutorials,则删除该节点
  71.      */
  72.     public boolean modifigXML(String oldFileName,String newFileName){
  73.         boolean isOk = false;
  74.         try{
  75.             SAXReader reader = new SAXReader();
  76.             Document doc = reader.read(new File(oldFileName));
  77.             /**修改内容之一: 如果book节点中show属性的内容为yes,则修改成no*/
  78.             List list = doc.selectNodes("/books/book/@show");
  79.             Iterator iter = list.iterator();
  80.             while(iter.hasNext()){
  81.                 Attribute attr = (Attribute)iter.next();
  82.                 if(attr.getValue().equals("yes"))
  83.                     attr.setValue("no");
  84.             }
  85.             /**
  86.              *修改内容之二: 把owner项内容改为Tshinghua
  87.              *并在owner节点中加入date节点,
  88.              * date节点的内容为2004-09-11,
  89.              * 还为date节点添加一个属性type
  90.              */
  91.             list = doc.selectNodes("/books/owner");
  92.             iter = list.iterator();
  93.             if(iter.hasNext()){
  94.                 Element owner = (Element)iter.next();
  95.                 owner.setText("Tshinghua");
  96.                 Element date = owner.addElement("date");
  97.                 date.setText("2006-07-30");
  98.                 date.addAttribute("type", "Gregorian calendar");
  99.             }
  100.            /**修改内容之三: 若title内容为Dom4j Tutorials,则删除该节点*/
  101.             list = doc.selectNodes("/books/book");
  102.             iter = list.iterator();
  103.             while(iter.hasNext()){
  104.                 Element elem = (Element)iter.next();
  105.                 Iterator iterElem = elem.elementIterator("title");
  106.                 if(iterElem.hasNext()){
  107.                     Element remTitle = (Element)iterElem.next();
  108.                     if(remTitle.getText().trim().equals("Dom4j Tutorials"))
  109.                         elem.remove(remTitle);
  110.                 }
  111.             }
  112.             //将doc中的内容写入文件中
  113.             try{
  114.                 FileWriter newFile = new FileWriter(new File(newFileName));
  115.                 XMLWriter newWriter = new XMLWriter(newFile);
  116.                 newWriter.write(doc);
  117.                 newWriter.close();
  118.             }catch(Exception e){
  119.                 e.printStackTrace();
  120.             }
  121.             isOk = true;
  122.         }catch(Exception e){
  123.             e.printStackTrace();
  124.         }
  125.         return isOk;
  126.     }
  127.     /**
  128.      *the method formatXML
  129.      *-------------------------
  130.      *默认的输出方式为紧凑方式,默认编码为UTF-8,
  131.      * 但对于我们的应用而言,一般都要用到中文,
  132.      * 并且希望显示时按自动缩进的方式的显示,这就需用到OutputFormat类。
  133.      */
  134.     public boolean formatXML(String fileName){
  135.         boolean isOk = false;
  136.         try{
  137.             SAXReader reader = new SAXReader();
  138.             Document doc = reader.read(new File(fileName));
  139.             XMLWriter formatWriter = null;
  140.             /**
  141.              *格式化输出,类型IE浏览一样
  142.              *指定XML编码
  143.              */
  144.             OutputFormat format = OutputFormat.createPrettyPrint();
  145.             format.setEncoding("gb2312");
  146.             formatWriter = new XMLWriter(new FileWriter(new File(fileName)), format);
  147.             formatWriter.write(doc);
  148.             formatWriter.close();

  149.             isOk = true;
  150.         }catch(Exception e){
  151.             e.printStackTrace();
  152.         }
  153.         return isOk;
  154.     }
  155.    /**
  156.      *the method readXML
  157.      */
  158.     public void readXML(String fileName){
  159.         try{
  160.             SAXReader reader = new SAXReader();
  161.             Document doc = reader.read(new File(fileName));
  162.             List list = doc.selectNodes("/books/book");
  163.             Iterator iter = list.iterator();
  164.             while(iter.hasNext()){
  165.                 Element book = (Element)iter.next();
  166.                 Iterator title = book.elementIterator("title");
  167.                 if(title.hasNext()){
  168.                     Element elemTitle = (Element)title.next();
  169.                     System.out.print("Title: "+elemTitle.getText());
  170.                     System.out.print(" Show: "+book.attributeValue("show")+"\n");
  171.                 }
  172.             }
  173.             
  174.             list = doc.selectNodes("/books/owner");
  175.             iter = list.iterator();
  176.             if(iter.hasNext()){
  177.                 Element owner = (Element)iter.next();
  178.                 System.out.println("Owner: "+owner.getText());
  179.                 System.out.println("Date: "+owner.elementText("date"));
  180.             }
  181.         }catch(Exception e){
  182.             e.printStackTrace();
  183.         }
  184.     }
  185.    /*
  186.     Title: Dom4j Tutorials Show: yes
  187.     Title: Lucene Studing Show: yes
  188.     Title: Lucene in Action Show: no
  189.    Owner: O'Reilly
  190.    Date: null
  191.     */
  192.     /**
  193.      *the method main
  194.      */
  195.     public static void main(String[] args){
  196.         long start = System.currentTimeMillis();//开始计时
  197.         Dom4jDemo dom4jDemo = new Dom4jDemo();
  198.         String fileName = "dom4jDemo.xml";
  199.         String newFileName = "new_dom4jDemo.xml";
  200.         System.out.println(fileName+"正在创建中...");
  201.         boolean isOk_create = dom4jDemo.createXML(fileName);
  202.         if(isOk_create) System.out.println(fileName+"创建成功!");
  203.         else System.out.println("创建失败!请检查后重新再试!");
  204.         
  205.         System.out.println("正在更新中...");
  206.         boolean isOk_modi = dom4jDemo.modifigXML(fileName, newFileName);
  207.         if(isOk_modi) System.out.println("恭喜,更新完成!");
  208.         else System.out.println("更新失败!请检查后重新再试!");
  209.         
  210.         System.out.println("正在格式化中...");
  211.         boolean isOk_format = dom4jDemo.formatXML(fileName);
  212.         if(isOk_format) System.out.println("恭喜,格式化完成!");
  213.         else System.out.println("格式化失败!请检查后重新再试!");
  214.         
  215.         System.out.println("正在读取文件 "+fileName+" ...");
  216.         System.out.println("------------------------------------------------");
  217.         dom4jDemo.readXML(fileName);
  218.         System.out.println("------------------------------------------------");
  219.         System.out.println(fileName+"读取成功!");
  220.         System.out.println("正在读取文件 "+newFileName+" ...");
  221.         System.out.println("------------------------------------------------");
  222.         dom4jDemo.readXML(newFileName);
  223.         System.out.println("------------------------------------------------");
  224.         System.out.println(fileName+"读取成功!");
  225.         System.out.println("一共耗时: "+(System.currentTimeMillis()-start)+"毫秒!");
  226.     }
  227. }

阅读(8070) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~