Replicate nodes with MarkBuilder in Groovy Script automatically
2023-11-15 17:18:52 Author: blogs.sap.com(查看原文) 阅读量:4 收藏

Hi all,

First of all, I’m not a groovy expert, so maybe there is another best option to achieve that but we have found it usefull for our expertise and some requirements that we have on the scope for other mappings.

This little code snippet is a great option when you need to modify a little bit your payload in SAP BTP Integration Suite with a Groovy Script using markBuilder class but you don’t want to replicate all fields of an specific subnodes.

The idea here is to call a function recursively to be able to replicate whatever you have below the subnode.

To achieve that we have this function:

void buildNodes(node, builder) {
    node.children().each { child ->
        if (child.children().size() > 0) {
            builder."${child.name()}"(child.attributes()) {
                buildNodes(child, builder)
            }
        } else {
            builder."${child.name()}"(child.attributes(), "${child.text()}")
        }
    }
}

the first variable is the xmlSlurper variable that we are using. And the second one is the markBuilder where we are defining our output.

So you should have something similar to this:

import groovy.xml.MarkupBuilder
import groovy.util.XmlSlurper
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.xml.XmlUtil

def Message processData(Message message) {
    def body = message.getBody(Reader)
    def parsedXml = new XmlSlurper().parse(body)

    // Some weird coding hacking the world or just an invoice

    // Create sorted InvoiceRequest
    def writer = new StringWriter()
    def xmlOutput = new MarkupBuilder(writer)
    
    xmlOutput.InvoiceRequest {
        Invoice {
                SupplierInvoiceID(parsedXml.Invoice.SupplierInvoiceID)
                SupplierInvoiceTypeCode(parsedXml.Invoice.SupplierInvoiceTypeCode)
                DocumentDate(parsedXml.Invoice.DocumentDate)
                items.each { item ->
                    Item {
                        buildNodes(item, xmlOutput)
                    }
                }
        }
    }

    message.setBody(writer.toString())
    return message
}

void buildNodes(node, builder) {
    node.children().each { child ->
        if (child.children().size() > 0) {
            builder."${child.name()}"(child.attributes()) {
                buildNodes(child, builder)
            }
        } else {
            builder."${child.name()}"(child.attributes(), "${child.text()}")
        }
    }
}



So, for example, testing it on a Groovy IDE we got this. Don’t worry, the payload is anonymized 🙂

GroovyIDE%20Example

GroovyIDE Example

Please comment below if you now a quickest way to achieve that! #WeGrowthAsAComunity


文章来源: https://blogs.sap.com/2023/11/15/replicate-nodes-with-markbuilder-in-groovy-script-automatically/
如有侵权请联系:admin#unsafe.sh