Skip to content

Instantly share code, notes, and snippets.

@yamen
Last active August 29, 2015 14:05
Show Gist options
  • Save yamen/4068f107724f8b4c81a2 to your computer and use it in GitHub Desktop.
Save yamen/4068f107724f8b4c81a2 to your computer and use it in GitHub Desktop.
// no type declarations needed
// optional semicolins
// literal string syntax
def myList = ['Hello', 'World']
// easy STDOUT printing
// optional method parentheses
println myList
import java.util.List;
import java.util.ArrayList;
List mylist = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
System.out.println(list);
// list literal syntax (java.util.List under the hood)
def aList = [1,2,[4,5,6]]
// map literal syntax (java.util.Map)
def aMap = [
'name' : 'Tom Smith',
'dob' : [
'year':1980,
'month':3,
'day': 20
]
]
def xml = new groovy.xml.MarkupBuilder()
xml.courses(year:"2013") {
courseName("Software Engineering")
courseName("Mechanical Engineering")
courseName("Electronics Engineering")
}
/* OUTPUT
<courses year='2013'>
<courseName>Software Engineering</courseName>
<courseName>Mechanical Engineering</courseName>
<courseName>Electronics Engineering</courseName>
</courses>
*/
def comment = "<![CDATA[<!-- address is new to this release -->]]>"
def builder = new groovy.xml.StreamingMarkupBuilder()
builder.encoding = "UTF-8"
// MAPPING
def person = {
// use mkp object which provides features like setting the namespace
mkp.xmlDeclaration()
mkp.declareNamespace('xsi':'http://www.w3.org/2001/XMLSchema-instance')
mkp.declareNamespace('ca':'http://org.org.org/xsd')
//start with the XML root node closure
ca.getEnrolledCoursesResponse {
//nested mapping
student{
identifier("96678963")
}
courseEnrolment {
status("ACTIVE")
phoneNumberProvided("true")
//use mkp object to set the CDATA comment
mkp.yieldUnescaped(comment)
}
}
}
// WRITING
def writer = new StringWriter()
writer << builder.bind(person)
println writer.toString()
/* OUTPUT
<?xml version="1.0" encoding="UTF-8"?>
<ca:getEnrolledCoursesResponse xmlns:ca='http://org.org.org/xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
<student>
<identifier>96678963</identifier>
</student>
<courseEnrolment>
<status>ACTIVE</status>
<phoneNumberProvided>true</phoneNumberProvided>
<![CDATA[<!-- address is new to this release -->]]>
</courseEnrolment>
</ca:getEnrolledCoursesResponse>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment