AKAI TSUKI

System development or Technical something

xslについて学ぶ2

xmlに対してxslを利用するためクラスはこんな感じで書けるらしいです。

package jp.sample.convert;

import java.io.File;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 * XMLを変換するためのユーティリティクラス.
 * 
 */
public class XMLConvertUtil
{
    /** 変換後に出力するファイルのエンコード. */
    private String outputEncodingKind_ = "Shift_JIS";

    /** 変換後に出力するファイルのパス(デフォルトはout.xml). */
    private String outXmlFilePath_ = "out.xml";

    /**
     * デフォルトコンストラクタ.
     */
    public XMLConvertUtil()
    {

    }

    /**
     * xmlファイルをxslファイルにより変換します.
     * 
     * @param xmlFilePath 変換データxmlファイルのパス
     * @param xslFilePath 変換定義xslファイルのパス
     * @throws TransformerException
     */
    public void convert(final String xmlFilePath, final String xslFilePath)
            throws TransformerException
    {
        File xmlFile = new File(xmlFilePath);
        File xslFile = new File(xslFilePath);

        File outXmlFile = new File(outXmlFilePath_);

        TransformerFactory factory = TransformerFactory.newInstance();

        Transformer transformer = factory.newTransformer(new StreamSource(xslFile));
        transformer.setOutputProperty(OutputKeys.ENCODING, this.outputEncodingKind_);

        transformer.transform(new StreamSource(xmlFile), new StreamResult(outXmlFile));

    }
}

XMLConvertUtilを使って実行するクラス

package jp.sample;

import jp.sample.convert.XMLConvertUtil;

/**
 * XMLの変換を実行する
 */
public class App
{
    /**
     * 実行を開始するクラス.
     * 
     * @param args 実行時の引数
     */
    public static void main(final String[] args)
    {

        String inXmlFilePath = "in.xml";
        String xslFilePath = "convert.xsl";

        XMLConvertUtil converter = new XMLConvertUtil();
        try
        {

            converter.convert(inXmlFilePath, xslFilePath);
        }
        catch (TransformerConfigurationException tce)
        {
            // TODO Auto-generated catch block
            tce.printStackTrace();
        }
        catch (TransformerException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}