First they ignore you
then they ridicule you
then they fight you
then you win
    -- Mahatma Gandhi
Chinese => English     英文 => 中文             
随笔-221  评论-1047  文章-0  trackbacks-0
利用Java来生成‘漂亮’的XML文件向来是一件比较麻烦的事,这里我通过Groovy来生成XML文件,代码十分简洁直观:

import  groovy.xml.MarkupBuilder

def out 
=   new  StringWriter()
def xml 
=   new  MarkupBuilder(out)

def friendList 
=  [ ' Tony ' ' Alan ' ' Leona ' ' Cloudy ' ' terry ' ]

xml.person {
    name(type:
" 网名 " , "山风小子")
    address 
"上海"
    friends(num: friendList.size()) {
        
for (f in friendList) {
            friend f
        }
    }
}

println out.toString()

输出结果:
< person >
  
< name  type ='网名'>山风小子</name>
  
<address > 上海 </ address >
  
< friends  num ='5'>
    
<friend > Tony </ friend >
    
< friend > Alan </ friend >
    
< friend > Leona </ friend >
    
< friend > Cloudy </ friend >
    
< friend > terry </ friend >
  
</ friends >
</ person >

在代码中,我使用了groovy.xml.MarkupBuilder,它是Groovy builder家族的一员,常用它来生成XML文件。
 
作为练习,您不妨尝试一下用它来生成一个HTML文件。

目标文件
<html>
  
<body>
    
<font color='red' size='6'>
      
<b>Hello, world!</b>
    
</font>
  
</body>
</html>

答案
import  groovy.xml.MarkupBuilder

def out  
=   new  StringWriter()
def html  
=   new  MarkupBuilder(out)

html.html {
    body {
        font(color:
'red', size:6) {
            b 
"Hello, world!"
        }
    }
}

println out.toString()

附:朝花夕拾——Groovy & Grails

posted on 2007-05-30 19:13 山风小子 阅读(4714) 评论(4)  编辑  收藏 所属分类: Groovy & Grails