I am trying to use Postgres to generate a single XML document as output.
Assume that I have a single relation, customers
. It has the columns id
, name
and email
.
I want XML that looks like this:
<customers>
<customer>
<id>0<id/>
<name>Customer 1<name/>
<email>customer1@gmail.com<email/>
<customer/>
<customer>
<id>1<id/>
<name>Customer 2<name/>
<email>customer2@gmail.com<email/>
<customer/>
<!--and so on-->
<customers/>
So far, I can generate the XML for each customer, like this:
SELECT XMLELEMENT(NAME customer,
XMLELEMENT(NAME 'id', "id"),
XMLELEMENT(NAME 'name', name),
XMLELEMENT(NAME email, email))
FROM customers;
However, concatenating this into a single XML document does not work. I have tried:
SELECT XMLELEMENT(NAME customers, XMLCONCAT((
SELECT XMLELEMENT(NAME customer,
XMLELEMENT(NAME 'id', "id"),
XMLELEMENT(NAME 'name', name),
XMLELEMENT(NAME email, email))
FROM customers;
)));
However, this fails with the message more than one row returned by a subquery used as an expression
.