WEB开发网
开发学院软件开发Java 实战 Groovy: 构建和解析 XML 阅读

实战 Groovy: 构建和解析 XML

 2009-11-18 00:00:00 来源:WEB开发网   
核心提示: 清单 8. 经过扩展的 MarkupBuilder 示例defsw=newStringWriter()defxml=newgroovy.xml.MarkupBuilder(sw)xml.langs(type:"current",count:3,mainstream:true)


清单 8. 经过扩展的 MarkupBuilder 示例
def sw = new StringWriter() 
def xml = new groovy.xml.MarkupBuilder(sw) 
xml.langs(type:"current", count:3, mainstream:true){ 
 language(flavor:"static", version:"1.5", "Java") 
 language(flavor:"dynamic", version:"1.6.0", "Groovy") 
 language(flavor:"dynamic", version:"1.9", "JavaScript") 
} 
println sw 
 
//output: 
<langs type='current' count='3' mainstream='true'> 
 <language flavor='static' version='1.5'>Java</language> 
 <language flavor='dynamic' version='1.6.0'>Groovy</language> 
 <language flavor='dynamic' version='1.9'>JavaScript</language> 
</langs> 

通过这些 MarkupBuilder 技巧,您可以实现一些有趣的功能。举例来说,您可以快速构建一个格式良好的 HTML 文档,并将它写出到文件中。清单 9 显示了相应的代码:


清单 9. 通过 MarkupBuilder 构建 HTML
def sw = new StringWriter() 
def html = new groovy.xml.MarkupBuilder(sw) 
html.html{ 
 head{ 
  title("Links") 
 } 
 body{ 
  h1("Here are my HTML bookmarks") 
  table(border:1){ 
   tr{ 
    th("what") 
    th("where") 
   } 
   tr{ 
    td("Groovy Articles") 
    td{ 
     a(href:"http://ibm.com/developerworks", "DeveloperWorks") 
    } 
   } 
  } 
 } 
} 
 
def f = new File("index.html") 
f.write(sw.toString()) 
 
//output: 
<html> 
 <head> 
  <title>Links</title> 
 </head> 
 <body> 
  <h1>Here are my HTML bookmarks</h1> 
  <table border='1'> 
   <tr> 
    <th>what</th> 
    <th>where</th> 
   </tr> 
   <tr> 
    <td>Groovy Articles</td> 
    <td> 
     <a href='http://ibm.com/developerworks'>DeveloperWorks</a> 
    </td> 
   </tr> 
  </table> 
 </body> 
</html> 

上一页  1 2 3 4 5 6 7 8 9 10  下一页

Tags:实战 Groovy 构建

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接