on 2024 Aug 26 2:41 PM
Dear CPI experts.
Good day,
Looking to get assistance with my requirement below.
The idea is to remove all below reserved characters from inside the all XML nodes if they are present.
However below script im trying to work with, but does not work. It is not preserving the XML structure hence the entire output is incorrect.
reserved characters *%?:;=()[]|#@
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.xml.XmlUtil
import groovy.util.XmlSlurper
def Message processData(Message message) {
def body = message.getBody(String)
def root = new XmlSlurper().parseText(body)
def cleanNodeContent
cleanNodeContent = { node ->
if (node instanceof groovy.util.slurpersupport.NodeChild) {
if (node.text()) {
// Remove reserved characters: *%?:;=()[]|#@
def cleanedText = node.text().replaceAll('[*%?:;=()\\[\\]\\|#@]', '')
node.setValue(cleanedText)
}
}
node.children().each { child ->
cleanNodeContent(child)
}
}
cleanNodeContent(root)
def cleanedXml = XmlUtil.serialize(root)
message.setBody(cleanedXml) // Set the modified body back to the message
return message
}
#
Request clarification before answering.
Example XML body with reserved characters -
<employees>
Groovy script to remove all reserved characters and keep the XML structure intact.
import com.sap.gateway.ip.core.customdev.util.Message
import java.util.regex.Pattern
def Message processData(Message message) {
def body = message.getBody(String)
// Define reserved characters and pattern
def reservedChars = ['*', '%', '?', ':', ';', '=', '(', ')', '[', ']', '|', '#', '@']
def pattern = reservedChars.collect { Pattern.quote(it) }.join('|')
// Function to clean reserved characters from XML content
def cleanContent = { content ->
return content.replaceAll(pattern, '')
}
// Replace reserved characters in XML content manually
def cleanedBody = body.replaceAll(/(<[^>]+>)([^<]*)(<\/[^>]+>)/) { match ->
def startTag = match[1]
def content = match[2]
def endTag = match[3]
return startTag + cleanContent(content) + endTag
}
// Set cleaned XML body
message.setBody(cleanedBody)
return message
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
88 | |
10 | |
9 | |
8 | |
7 | |
6 | |
6 | |
5 | |
5 | |
5 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.