Search code examples
mulemule-studiomule-esbmulesoft

Parsing CSV file and get a value of the filed from it


Question regarding Mule 4 and DWL syntax. I have a file listener that is expecting a csv file.
let say the file is in this format
value1, value2, value3, value4
Then I have a "var" message processor and in there need to assign the value of value3 (third field) to a variable. How can I dod that? Your help is appreciated.


Solution

  • If you only have the one line you can access the first row using index 0: [0], then access the third field using index 2 [2]. Indexes start at 0.

    Note, if your CSV does NOT have a header row, make sure to add this to the file:listener outputMimeType="application/csv;header=false" to let dw know there is no header row:

    <flow name="csv">
            <file:listener directory="/path/to/dir"  outputMimeType="application/csv;header=false" >
                <scheduling-strategy >
                    <fixed-frequency frequency="100000" />
                </scheduling-strategy>
            </file:listener>
    
            <logger level="INFO" message="#[payload]" />
            <set-variable value="#[output application/java --- payload[0][2] as String]" variableName="myVar" />
    
            <logger level="INFO" message="#[vars.myVar]" />
        </flow>
    

    Also note you can use the transform component to set-variables also for more complex transformations where better formatting is required:

    <ee:transform>
                <ee:variables>
                    <ee:set-variable variableName="myVar" ><![CDATA[%dw 2.0
    output application/java
    ---
    payload[0][2] as String]]></ee:set-variable>
                </ee:variables>
            </ee:transform>