3

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?

2
  • I get AT&T in 9.2. Where are you outputting that value? Commented Jan 9, 2013 at 13:08
  • SELECT version(); --> "PostgreSQL 9.0.4, compiled by Visual C++ build 1500, 32-bit" in pgAdmin3 Version 1.12.3 (Apr. 15 2011 REL-1_12_3) Commented Jan 9, 2013 at 16:00

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

Comments

1

If you are writing to an HTML client then you will have to HTML escape that for it to show the raw HTML.

As I see you are mainly a C# developer then the static method HttpUtility.HtmlEncode() will do it.

1 Comment

@Quandary I don't understand your comment.
0
CREATE OR REPLACE FUNCTION encode_xml_escape(s TEXT) RETURNS TEXT AS $$
DECLARE
    TempString TEXT;
BEGIN
    TempString := REPLACE(s, '&', '&amp;');
    TempString := REPLACE(TempString, '"', '&quot;');
    TempString := REPLACE(TempString, '''', '&apos;');
    TempString := REPLACE(TempString, '<', '&lt;');
    TempString := REPLACE(TempString, '>', '&gt;');
    RETURN TempString;
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE FUNCTION decode_xml_escape(s TEXT) RETURNS TEXT AS $$
DECLARE
    TempString TEXT;
BEGIN
    TempString := REPLACE(s, '&quot;', '"');
    TempString := REPLACE(TempString, '&apos;', '''');
    TempString := REPLACE(TempString, '&lt;', '<');
    TempString := REPLACE(TempString, '&gt;', '>');
    TempString := REPLACE(TempString, '&amp;', '&');
    RETURN TempString;
END;
$$ LANGUAGE plpgsql;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.