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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- What relations does the SQL touch?
- The references are `library`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.