We are executing the following postgres query:
select
AT.id,
AT.goal,
SS.id,
SS.index,
SS.goal,
TK.id,
TK.index,
TK.label,
TK.actions,
TK.type,
TK.group,
TK.blind,
TK.dynamic
from
automations as SS,
automation_sets as AT,
tasks as TK
where
SS.automation_set = 321
AND SS.automation_set = AT.id
AND TK.automation = SS.id
order by
SS.index, TK.index
which returns the following data:

How can use Postgres xml functions to aggregate the data in different XML levels, being the first level AT.ID+AT.goal and the second level SS.ID + SS.goal?
EDIT
We managed to get info we want but still have 1 issue... The SQL used is the following:
SELECT XMLELEMENT(name automation_set,
XMLATTRIBUTES(ASET_ID as id),
XMLAGG(xml_task_group))
FROM (SELECT AT.id as ASET_ID,
XMLELEMENT(name automation,
XMLATTRIBUTES(SS.goal as id),
XMLAGG(XMLELEMENT(name task,
XMLATTRIBUTES(TK.id as task_id, TK.label, TK.actions, TK.type, TK.group, TK.blind, TK.dynamic, TK.index)))) as xml_task_group
from
automations as SS,
automation_sets as AT,
tasks as TK
where
SS.automation_set = 321
AND SS.automation_set = AT.id
AND TK.automation = SS.id
group by
AT.id, SS.id
order by
SS.index) t
group by t.ASET_ID
but we are unable to get the order by TK.index, which is the task Index. We must make sure that they are in right order and we are unable to do it so far...