3

I'm producing XML right from PL/SQL in Oracle.

What is the preferred way of ensuring that outputted strings are XML-conformant, with regards to special characters and character encoding ?

Most of the XML file is static, we only need to output data for a few fields.

Example of what I consider bad practice:

DECLARE @s AS NVARCHAR(100)
SELECT  @s = 'Test chars = (<>, æøåÆØÅ)'

SELECT  '<?xml version="1.0" encoding="UTF-8"?>'
      + '<root><foo>'
      + @s
      + '</foo></root>' AS XML
3
  • From what are you making the XML? If you are using existing data look into XMLGEN functions. Commented Oct 28, 2009 at 18:38
  • I would tend to agree that using T-SQL syntax in an Oracle database should be considered Bad Practice ;) Commented Oct 29, 2009 at 3:07
  • @APC: Heh, thanks for the tip. (Yes, I'm a PL/SQL newbie) Commented Oct 29, 2009 at 14:55

3 Answers 3

2

There are two good ways to generate XML that I've found. One is the SYS.XMLDOM package which is essentially a wrapper around the Java DOM API. It's somewhat clunky because pl/sql doesn't have the polymorphic capabilities of Java, so you constantly have to explicitly "cast" elements to nodes and vice versa to use the methods in the package.

The coolest, IMO, technique is to use the XMLElement, etc, SQL functions like this:

SET SERVEROUTPUT ON SIZE 1000000;
DECLARE

    v_xml XMLTYPE;

BEGIN

    SELECT
        XMLElement( "dual",
            XMLAttributes( dual.dummy AS "dummy" )
        )
    INTO
        v_xml
    FROM
        dual;

    dbms_output.put_line( v_xml.getStringVal() );

END;
/

If your XML structure is not very complex and maps easily to your table structure then this can be very handy.

Sign up to request clarification or add additional context in comments.

Comments

2

Using XmlElement, XmlAttribute, ... is the best way to generate xml.
The following link gives a good intro in all functions there are:
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14259/xdb13gen.htm#ADXDB1620

If you look for some more ways, look at here
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14259/xdb13gen.htm#sthref1486

Whatchout for the encoding. If you run a pl/sql programm or a select generating xml in a client session. The xml is encoded with client codepage. If you run it in background job (using dbms_job or dbms_scheduler) it is encoded with database codepage.

Comments

1
select dbms_xmlgen.getXML('select * from yourtable');

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.