Convert Any(CSV,JSON,XML) to XML in DWL

Sandeep Sai Kumar Kancharla
2 min readApr 5, 2023

--

in this article I’m going to explain how can we convert Any(CSV,JSON,XML) to XML format, for that I build a DataWeave script to format any type of input(mentioned above) and any structure of input will convert into xml format.

it’s completely dynamic script there is no dependency of keys, values, type and structure of input.

%dw 2.0
output application/xml
/*
1.it will convert the any type/structure input to xml required format.
2.output of function anyToXml is in array format.
3.anyToXml accept two arguments like - anyToXml(arg1,arg2)
1. arg1 indicates the payload
2. arg2 indicates the type of payload
4.after exicution of anyToXml function our values come under root->rootItems->items
*/
fun anyToXml(inbound,dataType :String):Array =(
if(lower(inbound.^mediaType) contains "xml") "root":"rootItems" : "item" :inbound
else if(inbound is Object)(
if(dataType ~= "Object")
"root":"rootItems" : "item" : inbound
else
inbound
)
else if(inbound is Array) (
"root":"rootItems" : inbound map(
"item" : if($ is Object)
anyToXml($,"")
else anyToXml($,typeOf($))
)
)
else if(dataType ~= "Object")
inbound
else "root":"rootItems" : "item": inbound
)
---
anyToXml(payload, typeOf(payload))

below are the snippets for different inputs

JSON -> XML

this image shows how the json object data convert into xml format
json(object) to xml
this image shows how the json object data convert into xml format
json(array) to xml

CSV -> XML

this image shows how the csv data can convert into xml format
csv to xml

XML to XML

xml to xml

empty data to xml

empty string to xml
null to xml
single value to xml

any suggestions or comments or code issue(any format of input) please let me know so that I can improve the code

--

--