あるプログラマの日記

プログラマのメモ、出来事、考えたこと、勉強とかの雑記

インデント付きでXMLファイルを出力する。

  • org.apache.crimson.tree.XmlDocumentを使用する。(crimson.jar)

http://cvs.forge.objectweb.org/cgi-bin/cvsweb.cgi/c-jdbc/lib/crimson.jar?cvsroot=c-jdbc

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ... {
...
  /**
   * 指定ファイルにXMLドキュメントデータをインデント付きで書込む
   * @param file 出力ファイル
   */
  private static void write(File file) throws TransformerException, ParserConfigurationException{

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();

    // ルートのElementから最下層のElementまでの
    // XMLのDOMツリーを作成してdocument.appendChild()に引数
    // としてルートのElementインスタンスを渡す。
    document.appendChild( ... );

    OutputStream os = null;
    try{
      os = new FileOutputStream(file);
      ((XmlDocument)document).write( os );
    }catch(IOException ex){
      ex.printStackTrace();
    }finally{
      if(os != null){
        try{
          os.flush();
          os.close();
          os = null;
        }catch(IOException e){}
      }
    }
  }
...
}