DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Loading XML into MongoDB
  • Validate XML Request Against XML Schema in Mule 4
  • How to Convert JSON to XML or XML to JSON in Java
  • How to Connect to Splunk Through Anypoint Studio in 10 Steps

Trending

  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  1. DZone
  2. Coding
  3. Languages
  4. JSON to XML Transformation Using DataWeave

JSON to XML Transformation Using DataWeave

DataWeave can be used to transform JSON to XML. This example looks at an API that returns information about books in JSON with a backend that only accepts XML input.

By 
Swati Deshpande user avatar
Swati Deshpande
·
Jan. 20, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
34.3K Views

Join the DZone community and get the full member experience.

Join For Free

In this blog, I am going to explain how to transform JSON to XML using DataWeave. I will cover the use of variables and functions. I will also show the use of a couple of operators in DataWeave to achieve the desired output.

Let's take an example of an API that returns information about books in JSON. My backend only accepts XML input. The XML contains the total number of books. Books are sorted by the year in which they were published. Price for a particular book is displayed only if it is greater than 30.00.

Input JSON is in the following format:

[{
"title" : "Only Time Will Tell",
"author" : "Jeffrey Archer",
"year" : "2011",
"price" : "30.00"
}, {
"title" : "Private India: City on Fire",
"author" : "James Patterson",
"author" : "Ashwin Sanghi",
"year" : "2014",
"price" : "49.99"
}, {
"title" : "Harry Potter and the Goblet of Fire",
"author" : "J K. Rowling",
"year" : "2005",
"price" : "29.99"
}, {
"title" : "Twilight",
"author" : "Stephenie Meyer",
"year" : "2007",
"price" : "39.95"
}
]

Output XML is in this format:

<bks:bookstore xmlns:bks="http://example.com/bookstore">
<bks:totalBooks>4</bks:totalBooks>
<bk:book xmlns:bk="http://example.com/books" title="http://example.com/books/book?title='Harry Potter and the Goblet of Fire'">
<year>2005</year>
<author>J K. Rowling</author>
</bk:book>
<bk:book xmlns:bk="http://example.com/books" title="http://example.com/books/book?title='Twilight'">
<year>2007</year>
<price>39.95</price>
<author>Stephenie Meyer</author>
</bk:book>
<bk:book xmlns:bk="http://example.com/books" title="http://example.com/books/book?title='Only Time Will Tell'">
<year>2011</year>
<author>Jeffrey Archer</author>
</bk:book>
<bk:book xmlns:bk="http://example.com/books" title="http://example.com/books/book?title='Private India: City on Fire'">
<year>2014</year>
<price>49.99</price>
<author>James Patterson</author>
<author>Ashwin Sanghi</author>
</bk:book>
</bks:bookstore>

For achieving the desired result, execute the following steps.

1. Create a New Project in Anypoint Studio

Then, add HTTP Connector and configure it. Provide /bookstore as Base Path in Connector Properties.HTTP Connector

2. Add a Transform Message (DataWeave) Component

Define input and output metadata using above JSON and XML files as examples.Define Metadata

3. Remove {} in the DataWeave Code Section

We do this because we want to define our own code. Don't worry if any errors are shown.

4. Define namespaces in the DataWeave HeaderDefine Namespaces

5. Define the bookstore Element

Check Preview to see bookstore element generated.Define Bookstore

6. Enter payload in Curly Braces in the bookstore Element

We get errors because input payload is an array and XML is an object.Define Payload

7. Add Brackets Around payload

This will fix our errors. In Preview, I can see that elements from all key-value pairs in payload are generated.Fix Payload Errors

8. Add a Space and Then map {} After Payload

We do this because we want to iterate through all objects in input to create the book element. For this, we will have to use map operator. map Operator

9. Create book Element Inside Curly Braces in the map

Also define the year, price, and author elements as shown below.Define Elements

10. Use the map Operator on the author Element

In Preview, I see that the author element with value Ashwin Sanghi is not generated. This is because there are 2 key-value pairs in the second object in payload. So, it should be mapped as an array. For this, use map operator on author element as shown below and as seen in Preview, two author elements are generated.Define Author

11. Define the Attribute title 

We do this because we want to show the title of the book as an attribute of book. Define Title

12. Define a Variable With the Value as a URL

In the output XML, the title is displayed as a URL. For this, we will define the variable with the value as URL and then use a function for appending title to this URL, as shown below.Define Variables and Functions

13. Change the title Attribute to use the newUrl Function

In Preview, I can see that title of the book is generated in URL form.Title as URL

14. Use the when Operator to Check Price

In Preview, I can see that price element is not generated for all books. It is only generated if price is greater than 30.00. To handle this, use the when operator to check the price as shown below.when Operator

15. Use the orderBy Operator

Books are sorted by year in the output XML. I can achieve this using the orderBy operator and in Preview, we can see that books are sorted by year now.orderBy Operator

16. Show the Total Number of Books in the Output

We also want to show the total number of books in the output. Use the sizeOf operator for this.sizeOf Operator

To test this project, run the project in Anypoint Studio first. Once the project is successfully deployed, send input JSON as input to http://localhost:8081/bookstore using Postman or some other client for sending REST requests. In the response, I should get desired output XML as shown below.Postman Output

I have shown how to transform input JSON into output XML. I have also shown how to define namespaces used in output XML. Also, I have shown how we can declare variables and functions and how to use operators like map, when, orderBy, and sizeOf in DataWeave.

XML JSON

Opinions expressed by DZone contributors are their own.

Related

  • Loading XML into MongoDB
  • Validate XML Request Against XML Schema in Mule 4
  • How to Convert JSON to XML or XML to JSON in Java
  • How to Connect to Splunk Through Anypoint Studio in 10 Steps

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!