以前に作成した「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() メソッドのオーバーライド、使える!
- 作者: Dierk Konig,Andrew Glover,Paul King,Guillaume Laforge,Jon Skeet,杉浦孝,櫻井正樹,須江信洋,関谷和愛,佐野徹郎,寺沢尚史
- 出版社/メーカー: 毎日コミュニケーションズ
- 発売日: 2008/09/27
- メディア: 単行本(ソフトカバー)
- 購入: 5人 クリック: 146回
- この商品を含むブログ (121件) を見る