Skip to content

Instantly share code, notes, and snippets.

@robvalk
Created December 2, 2013 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robvalk/7747246 to your computer and use it in GitHub Desktop.
Save robvalk/7747246 to your computer and use it in GitHub Desktop.
Groovy mapping from Java Lists / Maps to XML (w3c DOM)
//import GroovyMap to get a handle to the transformation method - toXmlDom()
import au.com.sixtree.esb.mapper.GroovyMap
//DOMCategory to get us xpath style operations eg.getNode, getAttributes while traversing through the xml
import au.com.sixtree.java.esb.mapper.DOMCategory
import groovy.xml.XmlUtil;
//import static codeset cross-referencing helper class, see below for lookups
import au.com.sixtree.java.esb.mapper.ValueCrossReferenceHelper;
return GroovyMap.toXmlDom(payload) {
/*inputs is the args array, where the 0th element is the payload (passed in the line above)*/
def _in = inputs[0]
//use(Type){} - Construct to access xml elements
use(DOMCategory) {
/* add namespace to the output xml
* use builder object (@BuilderSupport) to create xml elements
* builder object (type NamespaceBuilder) has the declareNamespace(Comma_Seperated_Map), use that as a setter for namespaces
*/
builder.declareNamespace('xsi':'http://www.w3.org/2001/XMLSchema-instance' , 'ca':'http://sixtree.com.au/system/inboundadapter/v1/xsd')
//create root element and create its closure
builder.'ca:getBookInventoryResponse' {
// nested mapping for book with identifier
book {
name(_in[0].NAME)
identifier(_in[0].BOOK_ID)
//repeating field. Iterate over the inbound Map's keys enumeration
for(inventoryDetailsResponse in _in) {
inventoryDetails {
//xref lookup using a custom Java method
status(au.com.sixtree.esb.common.crossreferenceclient.ValueCrossReferenceHelper.lookup("Book Inventory Status", "Outbound_System_Name", inventoryDetailsResponse.INVENTORY_STATUS, "Inbound_System_Name"))
location {
city(inventoryDetailsResponse.CITY)
state(inventoryDetailsResponse.STATE)
}
inventoryCount(inventoryDetailsResponse.INVENTORY_COUNT)
}
}
}
}
}
}.map()//Serialize the entire closure to create an xml. Check the GroovyMap.map() method for more details
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment