DOM4j 学习笔记

 以前解析xml都是使用的w3c的一套api,今天尝试了一下dom4j,觉得还是比较好用的。下面简单介绍一下。

dom4j的官方网站是www.dom4j.org,你可以在http://www.dom4j.org/guide.html上找到简单的使用范例。

今天使用时碰到的问题是要在输出文件时在xml declaration中加入standalone=‘yes’这个属性,如果使用w3c的api,则只需要以下的代码:


 /**
  * Saves the dom tree to file.
  */
 public void saveDocument() throws Exception {
  File f = new File(outputFile);
  Document doc;

  doc = this.buildDocument();

  Transformer t = TransformerFactory.newInstance().newTransformer();

  // set the property
  t.setOutputProperty(OutputKeys.VERSION, "1.0");
  t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  t.setOutputProperty(OutputKeys.STANDALONE, "yes");

  t.transform(new DOMSource(doc), new StreamResult(
    new FileOutputStream(f)));
 }

但是使用dom4j时找了很久也没找到设置什么属性可以添加xml declaration中的属性,后来在查了一些资料后发现,必须自定义一个XMLWriter

代码如下:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;


/**
 * use to change the xml declararion
 * @author yiqian
 *
 */
public class MyXMLWriter extends XMLWriter {

 public MyXMLWriter(FileOutputStream fileOutputStream, OutputFormat format) throws UnsupportedEncodingException {
  // TODO Auto-generated constructor stub
  super(fileOutputStream,format);
 }

 @Override
 protected void writeDeclaration() throws IOException {
   OutputFormat format = getOutputFormat();

   String encoding = format.getEncoding();

   if (!format.isSuppressDeclaration()) {
     if (encoding.equals("UTF8")) {
       writer.write("<?xml version=/"1.0/"");

       if (!format.isOmitEncoding()) {
         writer.write(" encoding=/"UTF-8/"");
       }

       writer.write(" standalone=/"true/"");
       writer.write("?>");
     } else {
       writer.write("<?xml version=/"1.0/"");

       if (!format.isOmitEncoding()) {
         writer.write(" encoding=/"" + encoding + "/"");
       }

       writer.write(" standalone=/"yes/"");
       writer.write("?>");
   }

     if (format.isNewLineAfterDeclaration()) {
       println();
     }
   }
 }
 
这样相对应的代码就是:

 /**
  * Saves the dom tree to file.
  */
 public void saveDocument() throws Exception {
  File f = new File(outputFile);
  Document doc;

  doc = this.buildDocument();


  OutputFormat format = new OutputFormat("   ", true);
  XMLWriter writer = new MyXMLWriter(new FileOutputStream(f), format);
  writer.write(doc);
  writer.close();
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值