| From: | Färber, Franz-Josef (StMUK) <Franz-Josef(dot)Faerber(at)stmuk(dot)bayern(dot)de> |
|---|---|
| To: | "pgsql-general(at)lists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org> |
| Subject: | Extract text from XML, pay attention to XML Entities |
| Date: | 2026-09-16 15:35:15 |
| Message-ID: | 615fa488caa2422393498300d476dcc0@stmuk.bayern.de |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-general |
Dear Mailing List,
Let's say I want to extract from '<x>foo < bar</x>' the inner text "foo < bar" with XML Entity escape sequences resolved.
First attempt:
================
SELECT (xpath('/x/text()', '<x>foo < bar</x>'))[1]::text
... does not resolve the escape sequences: gives me "foo < bar"
Next attempt:
================
SELECT xpath_string('<x>foo < bar</x>', '/x/text()')
... works as intended, but
* the xml2 extension is deprecated
* won't deal with namespaces as far as I understand
Third attempt:
================
SELECT txt
FROM XMLTABLE('/x' PASSING '<x>foo < bar</x>' COLUMNS txt TEXT PATH '.')
works as intended, but if I want both namespaces and isolate this piece of code into a stored procedure, I have to deal with the XMLTABLE XMLNAMESPACE clause. And I suspect there is no freaking way to pass a parameter containing an array of namespace definitions into the XMLTABLE XMLNAMESPACE clause? (This I would consider a failure of SQL reusability.)
Any idea how to solve this fairly simple problem in a simple and general fashion? Thank You.
My last resorts would be
* using xpath(...)::text and replacing XML Entities *manually*
* or using XMLTABLE with dynamic SQL
* or: SELECT * FROM XMLTABLE('.' PASSING (xpath('/x', '<x>foo < bar</x>'))[1] COLUMNS txt TEXT PATH '.')
(Which shall mean: I can use xpath potentially passing namespace definitions as an array, and then use XMLTABLE for the single purpose of un-escaping the text.
Regards,
Franz-Josef Färber
P.S.: I have read:
Re: xpath does not seem to escape HTML correctly
https://www.postgresql.org/message-id/1409795403248-5817667.post%40n5.nabble.com
| From | Date | Subject | |
|---|---|---|---|
| Next Message | lakshmi | 2026-09-17 06:30:17 | Extension - ai_image_search: Image Search Inside PostgreSQL |
| Previous Message | Laurenz Albe | 2026-09-15 20:47:18 | Re: pg_upgrade --link |