Loading

How to escape special characters in XML format in Dataweave

Julkaisupäivä: Aug 5, 2025
Vaiheet

GOAL

This article will help in providing a solution for escaping special characters in XML format in Datweave.
There are five XML escape characters:
"   "
'   '
<   &lt;
>   &gt;
&   &amp;

PROCEDURE
This goal can be achieved in 2 ways:
1) By using replace function:
%dw 2.0
output application/json
---
payload map {
    ($ mapObject {
         ($$) :$ replace "&" with "&amp;" replace "<" with "&lt;" replace ">" with "&gt;" replace "\"" with "&quot;" replace "'"  with "&apos;"
    })
}

2) By using Apache Commons Lang Library in a CustomTransformer
%dw 2.0
output application/json
import java!org::apache::commons::text::StringEscapeUtils
fun escapeValues(e) =
  e match {
    case is Array  -> e map escapeValues($)
    case is Object -> e mapObject (v, k) -> {(k):StringEscapeUtils::escapeXml11(v)}
    else           -> e
  }
---
escapeValues(payload)

     While using method 2, please add the following dependency to the pom.xml file:
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>
  

REFERENCE:

http://commons.apache.org/proper/commons-lang/apidocs/index.html
https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents#
Knowledge-artikkelin numero

001116189

 
Ladataan
Salesforce Help | Article