Wednesday, January 6, 2010
Groovy流にXMLを扱う、XMLの読み書き変更
Groovyでは、JDOM等の既存ライブラリを使って XML を処理できますが、 Groovyに組み込まれた XmlSlurper クラスを等を使うと 非常に Groovy に処理できるようになります。
テスト 1
book/chapter/title の値を出力する例
def xmlinstance = """
<book>
<chapter>
<title>Introduction</title>
</chapter>
<chapter>
<title>Syntax</title>
</chapter>
</book>
"""
def book = new XmlSlurper().parseText( xmlinstance )
book.chapter.title.each{ println it }
Introduction と Syntax が出力されます。
テスト 2
book/chapter/title の先頭に番号を追加した上で、XMLを標準出力する例
def xmlinstance = """
<book>
<chapter>
<title>Introduction</title>
</chapter>
<chapter>
<title>Syntax</title>
</chapter>
</book>
"""
// input
def book = new XmlSlurper().parseText( xmlinstance )
// proc: タイトルの先頭に番号を追加
cnt = 0
book.chapter.each{
cnt++
it.title = cnt + '. ' +it.title.text()
println it.title.text()
}
// output
def builder = new groovy.xml.StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def osw = new OutputStreamWriter(System.out ,'UTF-8')
def writer = new PrintWriter(osw)
writer << builder.bind{
mkp.xmlDeclaration()
mkp.yield(book)
}
タイトルがそれぞれ...
- Introduction → 1. Introduction
- Syntax → 2. Syntax
に書き換えられて出力されます。
結果をファイルに出力する場合
writer を以下のようにFileWriterを使って書き換えれば、標準出力ではなく、ファイルに出力できます。
def writer = new FileWriter(new File('r.xml'))
補足) Windowsで実行する場合は...
$ groovy -c UTF-8 test2
