'deriving array values from yaml file

I have a requirement where my input XML is:

<Rule>
    <IdValueList>
        <RuleValue Id='Engineer' Value='Eng' />
        <RuleValue Id='Contractor' Value='IND' />
        <RuleValue Id='Doctor' Value='UK' />
        <RuleValue Id='Contractor' Value='KAR' />
    </IdValueList>
</Rule>

We need to validate firstly if attribute Id of element RuleValue (RuleValue.@Id) has value 'Contractor'. If it does not contain it then the message should not be processed further.

Next, we need to validate if the same RuleValue element has attribute @Value as either 'IND' or 'KAR'. If not, message should not be processed further.

Here is where I need help/inputs:

In a YAML file we need to store the values like ContractDetails = [{'IN','IND'},{'KA','BNG'}] for further processing.

If Contractor has a value of 'IND' Then it should be mapped to:

{
 geography : 'IN', 
 LineOfBusiness : 'IND'
} // from yaml file

If Contractor has a value of 'KAR' Then it should mapped to:

{
 geography : 'KA', 
 LineOfBusiness : 'BNG'
} // from yaml file


Solution 1:[1]

If you want to transform the XML input to the sample outputs one way to do it is to filter to leave only the element with the Id attribute equal to "Contractor", then transform it using the Value attribute as the key.

The ContractDetails provided is not valid YAML so I represented it as a valid YAML object, where the keys are the expected Value attributes, and the values are what we need to add to the output dynamically.

%dw 2.0
output application/json
var ContractDetails = read(
"ContractDetails:
    IND: 
        geography: IN
        LineOfBusiness: IND
    KAR:
        geography: KA
        LineOfBusiness: BNG"
    ,"application/yaml").ContractDetails
---
payload.Rule.IdValueList 
    filterObject ((value, key, index) -> key.@Id as String == "Contractor") 
    mapObject ((value, key, index) -> {
        geography: ContractDetails[key.@Value].geography,
        LineOfBusiness: ContractDetails[key.@Value].LineOfBusiness}
    )

Output:

{
  "geography": "IN",
  "LineOfBusiness": "IND"
}

If you read the YAML from a file you can use the p() operator to read the property instead of defining it inline (example var ContractDetails = p("ContractDetails")).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1