2011年1月24日月曜日

【Java】XMLからHTML(テーブル)を出力するプログラム。

さっきのCSVからXMLに変換するプログラムの続き。
出力されたXMLファイルを読み込んで、HTMLソース(CSVデータをテーブルに変換) するプログラム。
なんかロジック組んでたらDOMと Xerces(Apache XMLプロジェクトの) の両方のパーサ入り交じって非常にアレな動きしてます。
メインルーチンのロジックが汚いので直したいと思ったんですが力尽きたのでそのまま公開。

1/24日赤字部分を加筆修正。

以下ソース全量。

/* xml.java */

/**
* JavaでXMLファイルから文字を読み込み、HTMLのテーブル形式に変換してファイルに書き出すプログラム。
* 最後に実行するプログラム
*
* 2011/01/20
* Erlkonig
*/

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class xml {
   
    /* XML読み込み指定 */
    final static String url = ("D:/Java/CSV2XML/testdata/circledata.xml");            // 入力ファイル指定
   
    /* HTMLの出力、静的に生成するクラス */
    /**
     * ドキュメントタイプの宣言とHTMLタグの出力
     * @return
     */
   
    public String html() {
        String html = ("<!DOCTYPE html>\n<html lang =\"ja\">\n");
        return html;
       
    }
   
    /**
     * headタグの出力
     * @return
     */
   
    public String header() {   
        String header = ("\t<head>\n");
        return header;
    }
   
    /**
     * titleタグの
     * @return
     */
   
    public String title() {
        String title = ("\t\t<title>circlelist</title>\n");
        return title;
    }
   
    /**
     * headの閉じタグ
     * @return
     */
   
   
    public String headend() {
        String headend = ("\t</head>\n\n");
        return headend;
    }
   
    /**
     * bodyタグの出力
     * @return
     */
   
    public String body() {
        String body = ("\t<body>\n");
        return body;
        }
   
    /**
     * tableタグの出力
     * @return
     */
   
    public String table() {
        String table = ("\t\t<table>\n");
        return table;
    }
   
    /**
     * theadタグの出力
     * @return
     */
   
    public String thead() {
        String thead = ("\t\t<thead>\n");
        return thead;
    }
   
    /**
     * trタグの出力。何度か使う。
     * @return
     */
   
    public String tr() {
        String tr = ("\t\t\t<tr>\n");
        return tr;
    }
   
    /**
     * tr閉じタグの出力。何度か使う。
     * @return
     */
   
    public String trend() {
        String trend = ("\t\t\t</tr>\n");
        return trend;
    }
   
    /**
     * thead閉じタグの出力
     * @return
     */
   
    public String theadend() {
        String theadend = ("\t\t</thead>\n");
        return theadend;
    }
   
    /**
     * tfootタグの出力
     * @return
     */
   
    public String tfoot() {
        String tfoot = ("\t\t<tfood>\n");
        return tfoot;
    }

    /**
     * tfoot閉じタグの出力
     * @return
     */
   
    public String tfootend() {
        String tfootend = ("\t\t</tfood>\n");
        return tfootend;
        }
   
    /**
     * tbodyタグの出力
     * @return
     */
   
    public String tbody() {
        String tbody = ("\t\t</tbody>\n");
        return tbody;
        }
   
    /**
     * tbody閉じタグの出力
     * @return
     */
   
    public String tbodyend() {
        String tbodyend = ("\t\t</tbody>\n");
        return tbodyend;
        }
   
    /**
     * table閉じタグの出力
     * @return
     */
   
    public String tableend() {
        String tableend = ("\t\t</table>\n");
        return tableend;
    }
   
    /**
     * body閉じタグの出力
     * @return
     */
   
    public String bodyend() {
        String bodyend = ("\t</body>\n");
        return bodyend;
    }
   
    /**
     * HTML閉じタグの出力
     *
     * @return
     */

    public String htmlend() {
        String htmlend = ("</html>");
        return htmlend;
    }
    /* ここまで静的なHTMLタグ */
   
    /* メインメソッド */
    public void runner() {
        Node node;
        String str = null;
        String str2 = null;
        String data = null;
        FileWriter fw;                                            // ファイル出力
        try {
            fw = new FileWriter("D:/Java/CSV2XML/testdata/circledata.html");                        // 出力ファイル指定
            BufferedWriter bw = new BufferedWriter(fw);            //BufferedWriterオブジェクトbufferedwriterを生成;FileWriterオブジェクトoutFileを生成
            /* HTMLの静的な内容の出力(ヘッダ) */
            bw.write(html());
            bw.write(header());
            bw.write(title());
            bw.write(headend());
            bw.write(body());
            bw.write(table());
            bw.write(thead());
            bw.write(tr());
            /* ここまでHTMLの静的な内容の出力(ヘッダ) */
           
            /*ドキュメントの解析 */
            try {
                DOMParser parser = new DOMParser();                     // パーサの生成
                parser.parse(url);                                        // XMLファイルのパース
                Document document = parser.getDocument();    // DOCUMENTノードの取得
               
                /* 見出し項目を設定 */
               
                Node nod = document.getFirstChild();
                while (nod != null) {                        // ノード名だけを取得するロジック
                    str = null;
                    str = putNodeData(nod);
                    while (str == null) {
                        nod = nod.getFirstChild();
                        str = putNodeData(nod);
                    }
                    String label = ("\t\t\t\t<th>" + str.replace("_","") + "</th>\n");
                    bw.write(label);
                    nod = nod.getNextSibling();                // 兄弟ノードを取得
                }
               
                bw.write(trend());
                bw.write(theadend());
               
                bw.write(tfoot());
                bw.write(tfootend());
               
                /* 見出し項目設定終わり */
               
                /* データの取得と設定 */
               
                bw.write(tbody());
               
                DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = dbfactory.newDocumentBuilder();
                Document doc = builder.parse(url);                        // パースを実行してDocumentオブジェクトを生成
                Element root = doc.getDocumentElement();                // ルート要素を取得
               
                node = root;
                NodeList nodes = node.getChildNodes();
                Node nod2 = document.getFirstChild();
                for (int i = 0; i < nodes.getLength(); i++) {            // テキストデータだけを取得するロジック
                    bw.write(tr());
                    while (nod2 != null) {
                        str2 = null;
                        str2 = putNodeData(nod2);
                        while (str2 == null) {
                            nod2 = nod2.getFirstChild();
                            str2 = putNodeData(nod2);
                        }
                       
                        if (str2.matches("_" + ".*")) {                    // 上記の状態ではノード名を取得している状態。更に子ノードを取得する
                            nod2 = nod2.getFirstChild();
                            str2 = putNodeData(nod2);
                            if (str2.matches("http://" + ".*")) {
                                data = ("\t\t\t\t<td><a href=\"" + str2 + "\" target=\"_blank\">" + str2 + "</td>\n");
                            } else {
                                data = ("\t\t\t\t<td>" + str2 + "</td>\n");
                            }

                            bw.write(data);
                            nod2 = nod2.getParentNode();
                            nod2 = nod2.getNextSibling();
                        }
                    }   
                    bw.write(trend());
                    nod2 = nodes.item(i+1);
                }   
                bw.write(tbodyend());
               
                /* ラベルの取得終わり */

                /* ここまでHTMLのテーブル内の出力 */

                /* HTMLの静的な内容の出力(フッタ) */
               
                bw.write(tbodyend());
                bw.write(tableend());
                bw.write(bodyend());
                bw.write(htmlend());
                /* HTMLの静的な内容の出力(フッタ) */
               
                /* 出力ファイルのクローズ */
               
                bw.close();
            } catch (IOException e) {                // DOMパーサが取得できなかった場合、エラーを返す。
                e.printStackTrace();
            }
           
        } catch (ParserConfigurationException e0) {
            System.out.println(e0.getMessage());
        } catch (SAXException e1) {
            System.out.println(e1.getMessage());
        } catch (IOException e2) {
            System.out.println(e2.getMessage());
        }
    }
   
    /**
     * ノード情報(ノード名またはノード値(テキスト))を取得する
     * @param node
     * @return
     */
   
    static private String putNodeData(Node node) {
        String data = null;
        String macName = node.getNodeName();
        String macWord = "_";
        if (macName.matches(".*"+ macWord + ".*")) {
            data =macName;               
        } else if(node.getNodeType() == Node.TEXT_NODE) {
            data = node.getNodeValue();
        }
        return data;
    }

    /**
     * メイン
     * @param args
     */
    public static void main(String[] args) {
        xml t = new xml();
        t.runner();
    }

}


0 件のコメント: