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”);
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.