Wednesday, April 19, 2017

Mule Dev Tricks: Using xpath3

Introduction

Even though today most web services using RESTful architecture, there are still a lot of legacy systems using SOAP. Handling xml file is challenging, if not difficult. Fortunately, Mule Application platform provide several utilities to alleviate the pain. The most powerful component is Dataweave, which is very handle to build SOAP request and handle responses. However, some cases, xpath3 is an easier solution. Sometimes it may be the best solution, for instance, if we want to split the xml payload based on certain node.

In this short article, I will introduce two use cases:

  1. Extract values from xml payload
  2. Split the payload

Use Case One: Extract Value Of An Element

Input Example

Here is the input:



    
        31bf3ce3d6bb1025d71346c6ec276bd6
    
    
        31bf3ce3d6bb1025d71348e2f1c26bdc
        35119960
    

I want to extract the value of Position_ID in the line of:

    35119960

Solution

There are two solutions in this case. The first is:

    #[xpath3('/*:Create_Position_Response/*:Position_Reference/*:ID[2]')]

The above MEL will assign position_id to 35119960. Note: XML node count starting from 1 not from 0 as in Java array.

The other better solution is the following:

#[xpath3('/*:Create_Position_Response/*:Position_Reference/*:ID[@*:type=\'Position_ID\']')]
Here is the trick is \/*:ID[@*:type=\'Position_ID\'].
  1. Refer element attribute using [@*:type]
  2. Escape the single quote with backslash \'

Use Case Two: Use xpath3 To Split Payload

Example Input

In this use case, I would like to extract the node of StockMovementData, so that I can process the data.



    
Warehouse Location idm1468201212 2016-04-13T11:55:30.263+10:00
YES 2016-04-13T11:55:30.263+10:00 30-80 client 7CAGL3G00 700030011 100 YES 2016-04-13T11:55:30.263+10:00 30-80 client 7CAGL3G00 700029911 100

Here is the mule flow:

Solution

    
        
        
        
        
        
        
            
        
        
    

The above flow, split the xml payload using the following xpath3 expression:


Complete Mule Flow Configuration




    
        
        
        
        
        
    
    
        
        
        
        
        
        
            
        
        
    


3 comments:

  1. Could you please edit this post. Missing input, and source

    ReplyDelete

  2. the blog is good and Interactive it is about Mulesoft API Developer it is useful for students and Mulesoft Developers for more updates on Mulesoft mulesoft Online training

    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-...