Search code examples
dataweavemule4

Mule 4 for each splitting XML payload


I am trying to split the below xml using for each and I persist each xml node into a database table. But for some reason the code is unable to split.

<?xml version="1.0" encoding="UTF-8"?>
<wd:Report_Data xmlns:wd="xxx.com">
   <wd:Report_Entry>
      <wd:fiscalYear>FY2023</wd:fiscalYear>
      <wd:postedDate>2023-03-02T12:32:05.796-08:00</wd:postedDate>
   </wd:Report_Entry>
   <wd:Report_Entry>
      <wd:fiscalYear>FY2023</wd:fiscalYear>
      <wd:postedDate>2023-03-02T12:32:05.796-08:00</wd:postedDate>
   </wd:Report_Entry>
</wd:Report_Data>

Below is my for each fragment

<foreach doc:name="For Each" doc:id="5d66e985-11c9-400b-855c-74f9247e7e50" collection="#[%dw 2.0&#10;output application/xml&#10;ns wd xxx.com&#10;-&#45;&#45;&#10;payload.wd#Report_Data.*wd#Report_Entry]">
<logger level="DEBUG" doc:name="Logger" message="APGLPayload #[payload]" />
</foreach>

The xml seems properly formed. Any help will be highly appreciated. I need in the xml format to write to a db table. I had no issue with json though.


Solution

  • To generate an array that could be used as a collection in the foreach scope you should output to application/java. XML doesn't even has the concept of an array, and it is less performant since it would have to be parsed again to be used in any way. In fact when outputting XML trying the expression in the DataWeave Playground fails trying to convert an array to string.

    Example outputting Java:

    %dw 2.0
    output application/java
    ns wd xxx.com
    ---
    payload.wd#Report_Data.*wd#Report_Entry