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

  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB
  • SmartXML: An Alternative to XPath for Complex XML Files

Trending

  • Understanding Java Signals
  • The Role of Retrieval Augmented Generation (RAG) in Development of AI-Infused Enterprise Applications
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • STRIDE: A Guide to Threat Modeling and Secure Implementation
  1. DZone
  2. Coding
  3. Languages
  4. Transforming XML Into Another XML With DataWeave

Transforming XML Into Another XML With DataWeave

In order to convert XML returned by API into a format accepted by the backend (still in XML format), we can use DataWeave.

By 
Swati Deshpande user avatar
Swati Deshpande
·
Jan. 25, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
32.4K 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 XML into another XML using DataWeave. I will show how the output changes for different output types. I will also cover how code can be automatically generated in DataWeave, how we can write our own code, and use a couple of operators in DataWeave.

Let's take an example of an API that returns information about a bill for a customer in XML. My backend also accepts XML input. However, along with customer and product details, this XML also contains the discount and total price of the product. For converting XML returned by API into a format accepted by the backend, I will use DataWeave.

Suppose the input XML has the following format:

<bill>
    <customer_details>
        <name>Example Company</name>
        <address>Pune, India</address>
    </customer_details>
    <products>
        <product>
            <description>Product 1</description>
            <quantity>2</quantity>
            <price>10</price>
        </product>
        <product>
            <description>Product 2</description>
            <quantity>5</quantity>
            <price>30</price>
        </product>
    </products>
</bill>

I want to convert it into the following format:

<bill>
	<customer_details>
		<name>Example Company</name>
        <address>Pune, India</address>
	</customer_details>
	<products>
		<product no="2">
			<description>Product 2</description>
			<quantity>5</quantity>
			<price>30</price>
			<discount>10.0%</discount>
			<product_price>135.0</product_price>
		</product>
	</products>
	<total_price>153.0</total_price>
</bill>

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 /bill as the Base Path in Connector Properties.HTTP Connector

2. Add Transform Message (DataWeave) Component

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

3. Remove {} in the DataWeave Code Section

Enter payload. Check Preview to see the output.XML_Output

4. Change Output Type to application/json

Check Preview. Changing output type generates a different output.Json Output

5. Change Output Type to application/csv 

Add payload.bill.products.*product in the DataWeave body. The preview will now show the output in CSV format.Csv Output

6. Change Output Type Back to application/xml

Create a bill element as shown below.Define Bill

7. Use the Drag and Drop Functionality

We do this to generate code. Drag customer_details from the input section on customer_details in the output section. As seen in the below screenshot, code is generated automatically for this mapping.Map Customer Details

8. Create a products Element

Put it after customer_details.Define Products

9. Use the map Operator

For generating product element, we will have to iterate through all of the product elements in the input. Define Map Operator

10. Calculate the Discount of the Products

We will first define variable discount and then calculate the discount. After this, we will use the ++ operator to show the discount as a percentage.Define Discount

11. Calculate price for Each Product

Check Preview to see if the price is calculated properly or not.Define Price

12. Calculate the Total Price for All Products

We will use the reduce operator on the products array as follows.Define Total

13. Define Attribute no

In the output XML, we see that product no is displayed as an attribute of the element product.Define Product No.

14. Use the filter Operator

We do this because in the output, we can also see that product information is displayed only when quantity is greater than 2. Define Filter

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

In this way, I have shown you how to transform XML into another XML. I have also shown how the output changes for different output types. Also, I have covered how code can be automatically generated in DataWeave, how to write your own code, and how to use of operators map, ++, reduce and filter in DataWeave.

XML

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB
  • SmartXML: An Alternative to XPath for Complex XML Files

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!