ラベル Java の投稿を表示しています。 すべての投稿を表示
ラベル Java の投稿を表示しています。 すべての投稿を表示

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();
    }

}


2011年1月23日日曜日

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

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

以下ソース全量。

/* 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;
        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);
                            String 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();
    }

}


【Java】CSVからXMLに変換するプログラム

ここ1週間ほどゴリゴリソース書いてたので公開。
Excelデータ(CSVで保存)  をXML形式に変換して出力するプログラム。
入出力のデータはソースの中で呼び出してます。
あと、Winでの使用を前提としていますので文字コードは全てShift_Jisでやってます。
UTF-8で出力したい場合はXMLヘッダ部分と文字コードの変換機能を実装する必要があります。

誰得ソースだけど好きに使っていいのよ。
といってもCSV読み込みロジック借り物だけど。

XML出力ロジックとか思いついたの適当に入れてるのでもっとスマートな方法あるよとかあればご連絡ください。

以下ソース全量

/* csv.java */

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

import java.io.*;
import java.util.*;

public class csv {
    public String inFile = null;
    private BufferedReader bufferedreader = null;
    private List<String> list = new ArrayList<String>();
   
    public csv() {
    }
   
/**
 * 入力バッファーを生成し、中身を書き出す。
 * @param inFile    CSVファイル名
 * @throws IOException
 */

    public csv(String inFile) throws IOException {                            // 指定したファイルがあるかチェック
        this.inFile = inFile;
        bufferedreader = new BufferedReader(new FileReader(inFile));        // BufferedReaderオブジェクトbufferedreaderを生成;FileReaderオブジェクトinFileを生成
        String stemp;
        while((stemp = bufferedreader.readLine()) != null){                // 読み込みデータが無くなるまで読み込み
            list.add(stemp);
        }
    }
   
/**
 * CSV内容格納リストを取得します。
 * @param CSV内容リスト
 * @throws IOException
 */

    public List<String> getList() throws IOException {
        return list;
    }
   
/**
 * CSVファイルの行数を取得します。
 * @return CSV行数
 */

    public int getRowNum() {
        return list.size();
    }
   
/**
 * CSVファイルの列数を取得します。
 * @return CSV列数
 */

    public int getColNum() {
        if (!list.toString().equals("[]")) {
            if (list.get(0).toString().contains(",")) {
                return list.get(0).toString().split(",").length;
            }else if (list.get(0).toString().trim().length() != 0) {
                return 1;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
   
/**
 * 指定されたインデックス内容を取得します(行)。
 *
 */
    public String getRow(int index) {
        if (this.list.size() != 0)
            return (String) list.get(index).toString().trim();
        else
            return null;
    }
   
/**
 * 開いて入力ファイルをクローズします。
 * @throws IOException
 */

    public void FileClose()throws IOException {
        this.bufferedreader.close();
    }
   
//ファイルをXML形式に変換
   
/**
 * XMLの内容をバッファに書き込む。
 * 入力したデータをXML形式に変換して出力します。
 * 中身はゴリゴリ文字列操作。
 */
 
    /**
     * ヘッダーの作成
     * @return ヘッダー
     */
   
    public String header(){   
        String header = ("<?xml version=\"1.0\" encoding=\"Shift_JIS\" standalone=\"no\"?>");
        return header;
    }
   
    /**
     * root要素として「データラベル」要素を生成
     * @return データラベル
     */
       
    public String root(){
        String root = ("データラベル");                                        // データラベルノード作成
        return root;
    }
   
    /**
     * サークルデータ要素を生成し、イベント名属性を追加
     * @return サークルデータ
     */
   
    public String volume(){
        String document = "サークルデータ";   
        String event = "イベント名";
        String named = "東方おかやま桃太郎まつり";   
        String volume = (document + " " + event + "=" + "\"" + named + "\"");
        return volume;
    }

/**
 * メインルーチン。
 * ファイル作成用コード
 * @throws IOException
 */

     public void editfile() throws IOException{
        csv cu = new csv("D:/Java/CSV2XML/testdata/circledata.csv");        // アドレス直打ちしてます。
        List<String> tt = cu.getList();
        for (Iterator<String> itt = tt.iterator();itt.hasNext();){            // CSVの内容をコンソールに出力
            System.out.println(itt.next().toString());
        }
       
        System.out.println("\n");
        FileWriter fw = new FileWriter("D:/Java/CSV2XML/testdata/circledata.xml");
        BufferedWriter bw = new BufferedWriter(fw);        //BufferedWriterオブジェクトbufferedwriterを生成;FileWriterオブジェクトoutFileを生成
        bw.write(header());
        String roottag = ("<" + root() + ">");
        bw.write(roottag);
       
        //ラベルのデータをセットしていく}
        String str1 = cu.getRow(0);
        String [] str2 = str1.split(",", 0);

        //データの中身をセットしていく
           
        for (int i = 0; i < cu.getRowNum()-1; i++){
            try{
                String volumetag = ("<" + volume() + ">");
                bw.write(volumetag);
               
                int j = i + 1;
                String dat1 = cu.getRow(j);
                String [] dat2 = dat1.split(",",0);

                //ラベルとデータ合成
                for (int n = 0; n < cu.getColNum(); n++){
                    String str3 = str2[n].replaceAll("\"","");
                    String label = ("<_" + str3 + ">");
                    String labelend = ("</_" + str3 + ">");
                    String data = dat2[n].replaceAll("\"","");
                   
                    String outdata = (label + data + labelend);
                    bw.write(outdata);

                }
                int doclen = volume().indexOf(" ");
                String volstr = volume().substring(0,doclen);
                String volumeend = ("</" + volstr + ">");
                bw.write(volumeend);
            } catch (IndexOutOfBoundsException e) {
            }
        }
       
        String rootend = ("</" + root() + ">");
        bw.write(rootend);
       
        cu.FileClose();
        bw.close();
       
    }
   

/**
 * メイン
 * @param args
 * @throws IOException
 */

    public static void main(String[] args) throws IOException {
        csv editfile = new csv();
        editfile.editfile();
    }
}