0

I am using PostreSQL 14.3. I am trying to put something similar to this as a PostgreSQL Function:

select xmlelement(name car, xmlforest(make, model))
from cars
    

and run it against a table like this:

table cars   make varchar(20)   model varchar(20)
    
data ('Dodge','Viper'), ('Ford','Thunderbird')
    

I am missing a root element and I cannot seem to add one.

I would like to see:

<cars>  
    <car><make>Dodge</make><model>Viper</model></car>  
    <car><make>Ford</make><model>Thunderbird</model></car>
</cars>

but what I get is:

<car><make>Dodge</make><model>Viper</model></car>
<car><make>Ford</make><model>Thunderbird</model></car>

1 Answer 1

1

This one works, using XMLAGG to aggregate all rows into a single document:

SELECT xmlelement(name cars, XMLAGG(x)) 
FROM (
    SELECT xmlelement(name car, xmlforest(make, model)) 
    FROM cars
) sub(x);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.