The Oracle hierachical or connect-by query is different from what you need. You can use a single query to generate the structure you need, but you need to use Oracle XML SQL functions. Here is a link to the Oracle document:
http://docs.oracle.com/cd/E11882_01/appdev.112/e16659/xdb13gen.htm#i1029583
and here is something you may end up with:
SELECT
XMLElement("CARTONS",
XMLAgg (
XMLElement("CARTON",
XMLForest(carton_id As "CARTON_ID", carton_name As "NAME"),
(
select XMLElement("ITEMS",
XMLAgg(
XMLElement("ITEM",
XMLForest(item_id As "ITEM_ID", description As "DESCRIPTION")
)
)
)
from ITEMS
where carton_id = c.carton_id
)
)
)
) As myxml
FROM CARTONS c
for producing:
<CARTONS>
<CARTON>
<ITEMS>
<ITEM></ITEM>
<ITEM></ITEM>
<ITEM></ITEM>
</ITEMS>
</CARTON>
<CARTON>
<ITEMS>
<ITEM></ITEM>
<ITEM></ITEM>
</ITEMS>
</CARTON>
</CARTONS>
The above query starts from your carton level. It will get more complex when you add shipment and order layers. You basically construct the structure in the query, but it is definitely doable.
I wish you were producing JSON from a REST API. Then you could try a PL/SQL framework I have done. This framework provides a utility to produce complex JSON structure from regular queries. In case that you or any other people are curious to know, here is a link to our site:
You may find some interesting examples in Section 5.3 of the [User Guide][1]