Search code examples
mulemule-studioanypoint-studiomulesoft

"How to group xml data in Mule3 anypoint studio"


I am doing the transformation from json to xml then have to group by department. I am using mysql database to get the employee and it's department. At the last transformer I have to group by Department.

This is my json that I am getting from database after doing transformation.

[
    {
        "id": 1,
        "Full Name": "Devendra",
        "Department": {
            "DepartmentName": "IT"
        }
    },
    {
        "id": 2,
        "Full Name": "Rohit",
        "Department": {
            "DepartmentName": "IT"
        }
    }
]

Then, I am doing json to xml transformation and getting this below result.

<?xml version="1.0" encoding="windows-1252"?>
<employees>
    <employee>
        <id>1</id>
        <FullName>Devendra</FullName>
        <Department>
            <DepartmentName>IT</DepartmentName>
        </Department>
    </employee>
    <employee>
        <id>2</id>
        <FullName>Rohit</FullName>
        <Department>
            <DepartmentName>IT</DepartmentName>
        </Department>
    </employee>
</employees>

Expected result: I need to show the result group by Department wise dynamically like below-

<?xml version="1.0" encoding="windows-1252"?>
<Departments>
    <Department>
        <DepartmentName>IT</DepartmentName>
        <employee>
            <id>1</id>
            <FullName>Devendra</FullName>
        </employee>
        <employee>
            <id>2</id>
            <FullName>Rohit</FullName>
        </employee>
    </Department>
</Departments>

How can I do this transformation?


Solution

  • json2xml:

    %dw 1.0
    %output application/xml
    ---
    Departments: payload groupBy $.Department.DepartmentName mapObject {
        Department: 
            {DepartmentName: $$} ++
            {($ map {
                employee: {
                    id: $.id,
                    FullName: $.'Full Name'
                }
            })
        }
    }
    

    xml2xml:

    %dw 1.0
    %output application/xml
    ---
    Departments: payload.employees groupBy $.Department.DepartmentName mapObject {
        Department: 
            {DepartmentName: $$} ++
            {($ map {
                employee: {
                    id: $.id,
                    FullName: $.FullName
                }
            })
        }
    }