Ashesh Nair
Ashesh Nair

Reputation: 327

Exporting SQL table as XML

I have three tables namely Customer, Download, Games in portgres with following fields,

|-----------|
| Customer  |
|-----------|
|  cust_ID  |
|-----------|
|   name    |
|-----------|
|  country  |
|-----------|

|-----------|
| Download  |
|-----------|
|  cust_ID  |
|-----------|
|  game_ID  |
|-----------|
|  version  |
|-----------|

|-----------|
|   Games   |
|-----------|
|  game_ID  |
|-----------|
|   name    |
|-----------|
|   price   |
|-----------|

i am in need to export the table data into an xml format as below,

<customers>
  <customer>
    <id>1</id>
    <name>value</name>
    <country>value</country>
    <games>
      <game>
        <game_id>1</game_id>
        <name>value</name>
        <price>value</price>
        <download_ver>value</download_ver>
      </game>
      <game>
        <game_id>3</game_id>
        <name>value</name>
        <price>value</price>
        <download_ver>value</download_ver>
      </game>
    </games>
  </customer>

I will have multiple customer entities under customers table. the column under the node is from Download table linked by game_id field.

select XMLELEMENT(name "warehouses",
        XMLAGG(
            XMLELEMENT(name "warehouse",
                XMLFOREST(
                    w.w_id,
                    w.w_name,
                    w.w_country))))
                    FROM warehouse w

Above code can query warehouse nodes, but how do i incorporate games node?

Upvotes: 1

Views: 76

Answers (1)

S-Man
S-Man

Reputation: 23746

demo: db<>fiddle

SELECT 
    xmlelement(name customers, 
        xmlagg(
            xmlelement(name customer, 
                xmlforest(cust_id, name, country, games)
            )
        )
    )
FROM (
    SELECT
        c.cust_id,
        c.name,
        c.country,
        xmlelement(name games, 
            xmlagg(
                xmlelement(name game, 
                    xmlforest(g.game_id, g.name, price)
                )
            )
        ) as games
    FROM
        customer c
    JOIN
        download d ON (c.cust_id = d.cust_id)
    JOIN
        games g ON (d.game_id = g.game_id)
    GROUP BY c.cust_id, c.name, c.country
    ORDER BY c.cust_id
) s

You need two steps because there are two aggregations:

In the subquery we aggregate the games per customer into a xmlelement "games" with xmlagg.

In the outer query we aggregate all customers (with their already aggregated games) into a xmlelement "customers".

Upvotes: 1

Related Questions