Search code examples
xmllinuxoracle-databaseplsqleol

PL SQL XMLDOM change line ending


I would like to know if there is a way to set EOL while writing xmldom to a file. Database is set on linux machine but I need to save it to a file with CR LF line ending and I really don't know how.


Solution

  • From your question, I'm assuming that you're using DBMS_XMLDOM. Unfortunately, the DBMS_XMLDOM.WRITETOFILE procedures don't really have many options to control the serialization/pretty-printing. My version (12.1) has an undocumented pflag argument, and by experimenting it looks like a value of 4 removes all whitespace and newlines. That's handy for some scenarios, but I don't think it's what you want.

    DBMS_XMLDOM.WRITETOFILE(doc, 'MY_DIR/xmltest1.xml', 4, 0); 
    

    Oracle pretty-prints using whatever kind of newlines are appropriate for your server (Windows, Unix). If you want to use a different kind of newlines, I think your best option is to print the XML to a CLOB, replace LF with CRLF, and then write the clob to a file.

    DECLARE
     rc sys_refcursor;
     doc DBMS_XMLDOM.DOMDocument;
     sdoc clob;
    BEGIN
     OPEN rc FOR SELECT * FROM ( SELECT rownum FROM dual CONNECT BY level < 50000 );
     doc := DBMS_XMLDOM.NewDOMDocument(xmltype( rc ));
     dbms_lob.createtemporary(sdoc, true);
     dbms_xmldom.writetoclob(doc, sdoc);
     sdoc := replace(sdoc, chr(10), chr(13)||chr(10));
     DBMS_XSLPROCESSOR.clob2file(sdoc, 'MY_DIR', 'xmltest_crlf.xml');
    END; 
    /
    

    (This sample code assumes you have a directory named MY_DIR that you can write to.)

    Check out this article for more details on XML-to-file performance.

    If this is a very large XML file and the replace() function has poor performance, you might consider using the linux command unix2dos on the output file instead.