倭マン's BLOG

くだらない日々の日記書いてます。 たまにプログラミング関連の記事書いてます。 書いてます。

org.dom4j.Document を構築するビルダー・改

以前に作成した「org.dom4j.Document を構築するのビルダー」をちょこっと修正(一覧)。

以前のものは、createNode() メソッドでノードを作る際に、current プロパティを読み込んでルートノードかどうかを判断し、Element か Document のうち適切な方のインスタンスを返していました。 今回は createNode() で作るノードは Element オブジェクトだけにして、ルートノードの場合には postNodeCompletion() メソッドが Document オブジェクトを返すようにします。

サンプル・コード


サンプル・コードはこんな感じ。

def builder = new SimpleDom4jBuilder()
def doc = builder.table(customer:'c', invoice:'i'){
    join(c:'invoice_id', i:'id')
    and{
        greater('i.total':1000)
        like('c:name':'%Bill%', 'child')
    }
}

 assert doc instanceof org.dom4j.Document   

前回と同じです。

SimpleDom4jBuilder の実装


今回実装するメソッドは

  • protected createNode(name, Map atts, text) メソッド
  • protected setParent(parent, child) メソッド
  • protected postNodeCompletion(parent, child) メソッド

です。

createNode() メソッド

createNode() メソッドの実装は 「org.dom4j.Element を構築するビルダー」の場合と同じです(フルの引数の createNode() メソッドだけ載せておきます):

    @Override
    protected createNode(name, Map atts, text) {
        def e = this.factory.createElement(name.toString())

        atts.each{ attName, value ->
            e.addAttribute(attName.toString(), value.toString())
        }

        if(text != null){
            e.addText(text.toString());
        }

        return e
    }

setParent() メソッド

setParent() メソッドの実装は、これまた「org.dom4j.Element を構築するビルダー」の場合と同じです:

    @Override
    protected void setParent(parent, child) {
        parent.add(child)
    }

postNodeCompletion() メソッド

最後に、今回の実装のミソ、postNodeCompletion() メソッドの実装です:

    @Override
    protected postNodeCompletion(parent, node) {
        def result = super.postNodeCompletion(parent, node);
        if(parent != null){
            return result
        }else{
            return this.factory.createDocument(result)
        }
    }

引数の parent が null の場合はルート要素なので、Document オブジェクトを返しています。 それ以外の場合は通常の返り値(createNode() メソッドの返り値)を返します。

postNodeCompletion() メソッドのオーバーライド、使える!

Groovyイン・アクション

Groovyイン・アクション