RESTful初探之五(Generating XML documents)

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来简化。

Leveraging Groovy
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。
               
<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>


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()方法,然后引导到所期望的元素和属性。

def root = new XmlSlurper().parseText(raceXML)
def name = [email protected]()

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如下:

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()


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").

你可能感兴趣的:(document)