How to conditionally insert element in XML using MuleSoft DataWeave 2.0

My input xml is :

<?xml version='1.0' encoding='UTF-8'?>
<HRPeopleMaster>
  <Employee>
    <EmployeeID>123456</EmployeeID>
    <LastName>surname1</LastName>
    <FirstName>abc</FirstName>
  </Employee>
  <Employee>
    <EmployeeID>56789</EmployeeID>
    <LastName>surname2</LastName>
    <FirstName>xyz</FirstName>
  </Employee>
 </HRPeopleMaster>

I have a variable which contains a JSON array:

`var hroutput = [ {"customString": "10526","userId": "123456"},{"customString": "10551","userId": "45678"}]`

I want to insert the field customstring from this variable into the above xml only if the vars.hroutput.userId == Employee.EmployeeID condition is met.

So the final output should look like this:

`<?xml version='1.0' encoding='UTF-8'?>
<HRPeopleMaster>
  <Employee>
    <EmployeeID>123456</EmployeeID>
    <LastName>surname1</LastName>
    <FirstName>abc</FirstName>
    <customString>10526</customString>
  </Employee>
  <Employee>
    <EmployeeID>56789</EmployeeID>
    <LastName>surname2</LastName>
    <FirstName>xyz</FirstName>
    <customString/>
  </Employee>
 </HRPeopleMaster>`

Please guide me on how I can achieve this in a dataweave 2.0 script of Mulesoft

I tried to use the filter condition :

`{
    HRPeopleMaster: {
        (payload.HRPeopleMaster.*Employee map ( employee , indexOfEmployee ) -> {
            Employee: { FirstName: employee.FirstName
            } ++ (customString: (hroutput.customString) filter (hroutput.userId contains employee.EmployeeID)) 
        })
    }
}`

The output was like this:

`<?xml version='1.0' encoding='UTF-8'?>
<HRPeopleMaster>
  <Employee>
    <FirstName>Rajan</FirstName>
    <customString>10526</customString>
    <customString>10551</customString>
  </Employee>
  <Employee>
    <FirstName>Eamon</FirstName>
    <customString/>
  </Employee>
</HRPeopleMaster>`

Read more here: Source link