Wednesday 28 February 2024

how can we archive json to xml conversion in dataweave 2.0?84

 how can we archive json to xml conversion in dataweave 2.0?

DataWeave 2.0 offers functionalities to effectively convert JSON data into XML format. Here's a breakdown of the steps involved:

1. Define Data:

  • Start by establishing the JSON data you want to convert. This can be either:

  • Provided as input: If the JSON data is received as input to your Mule flow, you can access it using the payload variable.

  • Defined within the DataWeave script: You can directly define the JSON data structure as an object in your script:


%dw 2.0
output application/xml

var jsonData = {
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main Street",
    "city": "Anytown",
    "state": "CA"

2. Specify Root Element:

  • DataWeave requires a root element for the resulting XML output. This element will enclose all the converted data. Define the desired name for the root element:


// ... your JSON data definition

var rootElement = 'person'; // Define your desired root element name

3. Convert Data Using map and write:

  • Utilize the map function to iterate through the JSON data structure and convert it into the desired XML format.

  • Within the mapping, use DataWeave's syntax to construct the XML elements and their attributes.

  • Finally, use the write function to write the converted XML data to the output:


// ... your JSON data definition and root element

  rootElement @ ('xmlns:xsi': xsi, 'xmlns:xsd': xsd): {
    // Map over the JSON data using DataWeave expressions
    age: jsonData.age,
    address: {
      street: jsonData.address.street,
      state: jsonData.address.state


  • The map function iterates through each property-value pair in the JSON object.

  • DataWeave expressions like and jsonData.address.street access the corresponding values from the JSON structure.

  • Element names and attributes are defined within curly braces {}.

  • The @ symbol before the curly braces is used to add attributes to the root element.

Adapting the Code:

Remember to adjust the example code to match your specific JSON data structure and desired XML element names. You can use DataWeave's various functionalities like conditional expressions, comprehensions, and string manipulation functions to further customize the conversion based on your requirements.

By following these steps and adapting them to your specific data and needs, you can effectively achieve JSON to XML conversion using DataWeave 2.0 in your MuleSoft 4 applications.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.