Easy way to write SYS.XMLTYPE into a file using JAVA

It has been a while since my last post and I’m very sorry for that but I’m currently very busy in work as in my private life.

Yesterday I struggled a little bit around with generating xml from a select and put it into a plain text file. I needed a fast way to put the xml into a file for a temporary workaround so I didn’t really care about clean way to do this. The first part was pretty easy (generating xml from a select) but on the second part I wasted too much time for that simple task. Unfortunately also google wasn’t really helpful so I decided to put the few lines of code into my blog so that it’s documented for all the other peoples out there.

First part – Generate the XML using SQL/XML:

PreparedStatement stmt1 = Conn1.prepareStatement(“SELECT XMLELEMENT(\”TestSuite\”,” +
“(SELECT XMLAGG(XMLELEMENT(\”TestCase\”, XMLELEMENT(\”RuntimeInstanceId\”, instance_id)))” +
“FROM MYTESTS WHERE test_id = ?)).getclobval() as Result FROM dual”);
stmt1.setString(1, this.sTestId);
ResultSet result = stmt1.executeQuery();

The important thing here is the .getclobval() after the column in the select clause but first let’s see the second part.

Second part – Writing the XML to a plain text file:

Writer output = new BufferedWriter(new FileWriter(new File(this.sFile)));

That part looks now also pretty easy as you just can use result.getString(1) in here. But this is just possible because we called the getclobval() function in the select. This is a method of the XMLTYPE result object and will cast the result from XMLTYPE to CLOB. Without using getclobval() you will be surprised because result.getSQLXML(1) will simply not work. So if you need a fast way to write a XML to a plain text file just use getclobval() method of the XMLTYPE object.

3 thoughts on “Easy way to write SYS.XMLTYPE into a file using JAVA

  1. Hi, I had a similar requirement and I tried above but in my case getString(1) always returns NULL.
    Did you faced similar issue ? Can you please comment. Thanks


  2. Hi Anurodh,

    I did a few more tests and it always worked. So I guess that this is maybe different version error.

    I ran with JDBC Oracle driver against a database!




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.