Example 11-7: Generating XML for any SQL Query

import java.sql.*;
import java.io.*;

public class XMLForQuery {
  public static void print(String sql, String resultElt, String rowElt,
                           PrintWriter out) throws SQLException {
    Connection cn = null;
    ResultSet  rs = null;
    try {
      cn = Examples.getConnection();
      // Execute the sql statement to produce a ResultSet
      rs = cn.createStatement().executeQuery(sql);
      XMLForResultSet.print(rs,resultElt,rowElt,out);
    }
    catch (Exception e) {
      out.println("<?xml version=\"1.0\"?>"+
                  "<ERROR>"+
                    "<SQL>" +     sql        + "</SQL>"+
                    "<MSG>" + e.getMessage() + "</MSG>"+
                  "</ERROR>");
    }
    finally {
      // Clean up
      try {rs.close();cn.close();}
      catch (Exception e2) { /* Ignore */ }
    }
  }
}