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:
          " 網(wǎng)名 " , "山風小子")
          ????address?
          "上海"
          ????friends(num:?friendList.size())?{
          ????????
          for?(f?in?friendList)?{
          ????????????friend?f
          ????????}
          ????}
          }

          println?out.toString()

          輸出結(jié)果:
          < person >
          ??
          < name? type ='網(wǎng)名'>山風小子</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文件。
          ?
          作為練習(xí),您不妨嘗試一下用它來生成一個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 山風小子 閱讀(4743) 評論(4)  編輯  收藏 所屬分類: Groovy & Grails
          主站蜘蛛池模板: 额敏县| 茌平县| 三河市| 保亭| 武清区| 闽清县| 南安市| 汶上县| 武宣县| 三亚市| 肥城市| 德庆县| 乐都县| 凉城县| 绥阳县| 吐鲁番市| 大渡口区| 新乐市| 斗六市| 广灵县| 喀喇沁旗| 宁蒗| 闽清县| 临泉县| 龙游县| 桦南县| 固镇县| 神木县| 达日县| 平塘县| 黔江区| 长阳| 金塔县| 上蔡县| 安庆市| 益阳市| 肥西县| 九江市| 景宁| 星座| 如东县|