← Back to Groovy & JavaScript

Working with XML and JSON Payloads

Introduction to Scripting for Payloads

In SAP CPI, not all data transformations can be handled by the standard Message Mapping or XML Converter. For complex logic, dynamic routing, or when dealing with payloads that have complex structures, Groovy and JavaScript are essential. The Groovy language, in particular, offers powerful, built-in libraries for handling both XML and JSON data with ease.

Working with XML using Groovy's 'XmlSlurper'

The 'XmlSlurper' class is a simple and fast way to parse XML payloads. It treats the XML as a tree-like structure, allowing you to easily navigate to and access elements using a simple dot notation.

Example XML Payload:
<Products>
  <Product id="1001">
    <Name>Laptop</Name>
    <Price>1200.50</Price>
  </Product>
  <Product id="1002">
    <Name>Mouse</Name>
    <Price>25.00</Price>
  </Product>
</Products>
Example Groovy Script ('XmlSlurper'):
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.xml.*

def Message processData(Message message) {
    def xmlPayload = message.getBody(String.class)

    // Use XmlSlurper
    def slurper = new XmlSlurper(false, false) //XmlSlurper(boolean validating, boolean namespaceAware)
    def products = slurper.parseText(xmlPayload)

    // Find the price of the product with ID "1001" and set it as a header
    def laptop = products.Product.find { it.@id == '1001' }
    if (laptop) {
        def laptopPrice = laptop.Price.text()
        message.setHeader('LaptopPrice', laptopPrice)
    }

    // Modify the second product's name
    if (products.Product.size() > 1) {
        products.Product[1].Name.replaceBody('Wireless Mouse')
    }

    // Serialize back to XML string
    def updatedXml = XmlUtil.serialize(products)
    message.setBody(updatedXml)

    return message
}

Working with JSON using Groovy's 'JsonSlurper'

The 'JsonSlurper' class provides a similar, intuitive approach for parsing JSON payloads. It converts the JSON string into a native Groovy object (like a Map or a List), which you can then navigate using dot notation or array indexing.

Example JSON Payload:
{
  "user": {
    "id": "u1234",
    "name": "John Doe",
    "contact": {
      "email": "john.doe@example.com",
      "phone": "555-1234"
    },
    "roles": ["admin", "developer"]
  }
}
Example Groovy Script ('JsonSlurper'):
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper

def Message processData(Message message) {
    def jsonPayload = message.getBody(String.class)
    def jsonSlurper = new JsonSlurper()
    def parsedJson = jsonSlurper.parseText(jsonPayload)

    // Access the user's email and set it as a header
    def userEmail = parsedJson.user.contact.email
    message.setHeader('UserEmail', userEmail)
    
    // Access the second role in the 'roles' array
    def secondRole = parsedJson.user.roles[1]
    message.setHeader('SecondRole', secondRole)

    return message
}