Saturday, December 16, 2017

Mule Dev Tricks: Dataweave Working With XML Data

The Use Case

In my earlier post, I have explained the tricks using xpath3() to extract data from xml data. In this post I will demonstrate a use case to extract data using Dataweave.

Here is the input data (I omitted the not-interesting xml data:
...
            
                        
                            anshul.gupta277@gmail.com
                            
                                
                                    
                                        836cf00ef5974ac08b786079866c946f
                                        HOME
                                    
                                
                            
                        
                        
                            sudeshna.nanda@tcs.com
                            
                                
                                    
                                        1f27f250dfaa4724ab1e1617174281e4
                                        WORK
                                    
                                
                            
                        
            
...

The desired output is an arraylist:

[
     {
         email=anshul.gupta277@gmail.com, 
         wid=836cf00ef5974ac08b786079866c946f, 
         type=HOME
     }, 
     {
         email=sudeshna.nanda@tcs.com, 
         wid=1f27f250dfaa4724ab1e1617174281e4, 
         type=WORK
     }
]

The Solution

The following is the solution:
%dw 1.0
%output application/java
%namespace ns0 urn:com.workday/bsvc
---
payload.ns0#Get_Workers_Response.ns0#Response_Data.*ns0#Worker.ns0#Worker_Data.ns0#Personal_Data.ns0#Contact_Data.*ns0#Email_Address_Data
map {
 email: $.ns0#Email_Address,
 wid: $.ns0#Usage_Data.ns0#Type_Data.ns0#Type_Reference.*ns0#ID[?($.@ns0#type == "WID")][0],
 type: $.ns0#Usage_Data.ns0#Type_Data.ns0#Type_Reference.*ns0#ID[?($.@ns0#type == "Communication_Usage_Type_ID")][0]
}

The Key Learning Points

  1. Make array with wildcard *: ns0#Contact_Data.*ns0#Email_Address_Data
  2. Get expect element using: ns0#ID[?($.@ns0#type == "WID")][0]
  3. Remember: access attribute of a xml element using @

2 comments:

  1. Very informative post for mulesoft developers.You can also visit goformule.com for mulesoft stuff.

    ReplyDelete

Anypoint Studio Error: The project is missing Munit lIbrary to run tests

Anypoint Studio 7.9 has a bug. Even if we following the article: https://help.mulesoft.com/s/article/The-project-is-missing-MUnit-libraries-...