XMLElement And XPath Build And Query XML

Build XML fragments with xmlelement and xmlattributes, then xpath pulls attributes and child text out of each stored document.

SqlData Fetching

Code

snippet
-- xmlelement builds XML fragments, xmlattributes attach attributes; xpath query reads them back
SELECT xmlelement(NAME book,
    xmlattributes('sql' AS subject),
    xmlelement(NAME title, 'window functions'),
    xmlelement(NAME pages, 320)
) AS book_xml;

-- xpath 用路径表达式取属性
SELECT xpath('/book/@subject', xmlelement(NAME book,
    xmlattributes('sql' AS subject))) AS subject_attr;

WITH library AS (
    SELECT xmlelement(NAME book,
        xmlattributes('sql' AS subject),
        xmlelement(NAME title, 'window functions')
    ) AS doc
    UNION ALL
    SELECT xmlelement(NAME book,
        xmlattributes('xml' AS subject),
        xmlelement(NAME title, 'namespaces')
    )
)
SELECT
    (xpath('/book/@subject', doc))[1]::text AS subject,
    (xpath('/book/title/text()', doc))[1]::text AS title
FROM library
ORDER BY subject;

How the snippet works

The file runs SELECT statements, touching library.

The SQL constructs in play: a CTE (WITH … AS) that names an intermediate result before the main query; an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries.

Applying it

Run the statement against the library table.

Statements that hold the behavior

SELECT xmlelement(NAME book,
    xmlattributes('sql' AS subject),
    xmlelement(NAME title, 'window functions'),
    xmlelement(NAME pages, 320)
) AS book_xml;
SELECT xpath('/book/@subject', xmlelement(NAME book,
    xmlattributes('sql' AS subject))) AS subject_attr;

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `library`.