How can I create an XML file from PostgreSQL?
-
postgresql is DBMS , please be clearJigar Joshi– Jigar Joshi2011-02-11 08:54:58 +00:00Commented Feb 11, 2011 at 8:54
-
ok? but any code you have jigar.. i m just beginer...Siten– Siten2011-02-11 11:20:26 +00:00Commented Feb 11, 2011 at 11:20
-
@JigarJoshi Yes even if DBMS you can create XML file implicitly....................Royce– Royce2018-08-26 07:19:38 +00:00Commented Aug 26, 2018 at 7:19
4 Answers
Lets say you need to create following kind of XML
<Agents>
<agent id="32"/>
<agent id="33"/>
<agent id="34"/>
</Agents>
Then just run following query;
SELECT
XMLFOREST(tb1."xml-val" AS "Agents")
FROM
(
SELECT
XMLAGG(XMLELEMENT(NAME agent ,XMLATTRIBUTES(t.id AS id))) AS
"xml-val"
FROM
test t
) AS tb1;
:)
1 Comment
By using the XML functions:
http://www.postgresql.org/docs/current/static/functions-xml.html#AEN15086
4 Comments
Here is a stored procedure (called function in PostgresSQL) that returns XML from a simple query.
CREATE OR REPLACE FUNCTION getXml()
RETURNS xml
AS
$BODY$
DECLARE myXml xml;
BEGIN
SELECT * INTO myXml FROM query_to_xml_and_xmlschema('SELECT id FROM someTable', true, true, 'myProject.mySchema');
RETURN myXml;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION getXml() OWNER TO postgres;
Call the function by the select statement:
SELECT getXml();
The function will return a schema in XSD schema notation, and your data in XML rendered as an 'XML forest'.
Comments
This is my precise example to the question.
CREATE TABLE xml_mobile_data AS SELECT
xml $$
<rows>
<row id="1">
<model>Samsung Galaxy Note 9</model>
<price>$3,000.00</price>
</row>
<row id="2">
<model>iPhone X</model>
<price>$1,000.00</price>
</row>
<row id="3">
<model>Samsung Galaxy S9+</model>
<price>$999.00</price>
</row>
<row id="4">
<model>Huawei P20 Pro</model>
<price>$2,000.00</price>
</row>
<row id="5">
<model>Google Pixel XL 3</model>
<price>$899.00</price>
</row>
</rows>
$$ AS mobile_data;
We can retrieve this in row format.
SELECT xmltable.*
FROM xml_mobile_data,
XMLTABLE('/rows/row'
PASSING mobile_data
COLUMNS
ordinality FOR ORDINALITY,
model_id INT PATH '@id',
model TEXT PATH 'model',
"price" MONEY
);
Another way is the usage of WITH QUERY CTE(COMMON TABLE EXPRESSIONS)
WITH xmldata(data) AS (VALUES ('
<rows>
<row id="1">
<model>Samsung Galaxy Note 9</model>
<price>$3,000.00</price>
</row>
<row id="2">
<model>iPhone X</model>
<price>$1,000.00</price>
</row>
<row id="3">
<model>Samsung Galaxy S9+</model>
<price>$999.00</price>
</row>
<row id="4">
<model>Huawei P20 Pro</model>
<price>$2,000.00</price>
</row>
<row id="5">
<model>Google Pixel XL 3</model>
<price>$899.00</price>
</row>
</rows>
'::XML))
SELECT xmltable.*
FROM xmldata,
XMLTABLE('/rows/row'
PASSING data
COLUMNS
ordinality FOR ORDINALITY,
model_id INT PATH '@id',
model TEXT PATH 'model',
"price" MONEY
);