Thu, July 17, 2008
InDesignで書き出したXML文書の整形
InDesignで書き出したXMLは改行やスペースが入っていないため、 そのままテキストエディタで編集するには厳しいものがあります。
その場合に便利なJavaのコード。 (jdom.jarを使用します。)
Test.java
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class Test{
private static String ENC="UTF-8";
public Test(File xmlfile) throws Exception{
// 1. read xmldata
Document doc=new SAXBuilder().build(xmlfile);
// 2. ready xmloutputter
Format format=Format.getPrettyFormat();
format.setEncoding(ENC);
XMLOutputter out=new XMLOutputter(format);
// 3. output to STDOUT
Writer w=new OutputStreamWriter(System.out,ENC);
out.output(doc,w);
w.close();
}
public static void main(String[] args){
if(args.length==1){
File f=new File(args[0]);
try{
new Test(f);
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
}
実行
$ javac -classpath jdom.jar:. Test.java
$ java -cp jdom.jar:. Test sample.xml
整形されたXMLが標準出力されます。
整形前
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root>
<page>
<div>はじめにお読みください</div>
<div>ステレオデジタルボイスレコーダー 品番 123</div>
<div>このたびは本製品をお買い上げ頂き、誠にありがとうございます。</div>
</page>
</Root>
整形後
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<page>
<div>はじめにお読みください</div>
<div>ステレオデジタルボイスレコーダー 品番 123</div>
<div>このたびは本製品をお買い上げ頂き、誠にありがとうございます。</div>
</page>
</Root>