Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to XML-encode a string in PostgreSQL?

Question: I can create a XML-encoded string in Postgres like this:

SELECT xmlelement(name name, 'AT&T', null )

now I want to get the xml encoded value, that is to say AT&T.

But if I do:

SELECT unnest(xpath('/name/text()', xmlelement(name name, 'AT&T', null )))

then I get AT&T, not AT&T.

How can I get the XML-encoded value?

Furthermore, isn't it possible to supply an empty name to xmlelement, and just cast to varchar?

like image 616
Stefan Steiger Avatar asked Jul 11 '26 10:07

Stefan Steiger


1 Answers

I would suggest to use a simple function.

create or replace function xml_escape(s text) returns text as
$$
  select replace(replace(replace(s, '&', '&amp;'), '>', '&gt;'), '<', '&lt;');
$$
language sql immutable strict;
like image 122
Stefanov.sm Avatar answered Jul 14 '26 03:07

Stefanov.sm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!