RESTful初探之五(Generating XML documents)

4 篇文章 0 订阅
1 篇文章 0 订阅
[size=large]In the Formatting the resource,wo decided to leverage XML as the data mechanism for sharing information between clients and the service.your Restlets,therefore,must manipulate XML:build it in the case of a GET and consume it in the case of a POST,PUT,or DELETE.In this section,you'll take the pain out of generating and manipulating XML documents by leveraging the Groovy scriping language.
之前格式化resource中讲的,我们决定使用XML作为数据机制。但是XML的生成与操作非常痛苦,幸运的是,我们可以使用Groovy来简化。

[color=red]Leveraging Groovy[/color]
Working with XML is no easy chore.It can be tedious and error prone,to say the least.Fortunately,Groovy makes working with XML much easier.

You'll leverage Groovy's power to generate XML and do the tedious job of manipulating XML documents.Working with XML in Groovy couldn't be any easier.For instance,parsing an XML document is a cakewalk.Take the XML document in Listing7:
你将使用Groovy来生产和操作XML。
[/size]
<acme-races>
<race name="Alaska 200 below" date="Thu Jan 01" distance="3.2" id="20">
<uri>/races/20</uri>
<description>Enjoy the cold!</description>
</race>
</acme-races>


[size=large]Suppose you wanted to grab the value of the <race>element's name attribute.All you need to do is pass in an instance of the XML document to Groovy's XMLSlurper class,call the parse() method,and then navigate to desired element or attribute ,as shown in Listing8
假如你想获得<race>元素的name属性。你要做的就是将XML文件实例放入Groovy的XMLSlurper类中,调用parse()方法,然后引导到所期望的元素和属性。[/size]
def root = new XmlSlurper().parseText(raceXML)
def name = root.race.@name.text()

[size=large]If you want the description, it's as easy as calling root.race.description.text().
Creating XML is easy too. If you wanted to create the XML snippet in Listing 7, all you have to do is create an instance of Groovy's MarkupBuilder class and add nodes to it, as in Listing 9:
创建一个XML如下:
[/size]
def writer = new StringWriter()
def builder = new MarkupBuilder(writer)
builder."acme-races"() {
race(name: "Alaska 200 below", date: "Thu Jan 01", distance: "3.2", id: "20") {
uri("/races/20")
description("Enjoy the cold!")
}
}
println writer.toString()


[size=large]Note how elements are added to the XML document by attaching names to the builder instance. I had to put quotation marks around acme-races because hyphens aren't allowed in string literals in Groovy; consequently, making acme-races a String solves that problem nicely.
Elements can have attributes. Attribute names and values are created by constructing a Groovy map, which links the two together (for example, name:"Alaska 200 below").[/size]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值