This class is a utility to turn a Java ResultSet into xml. It's returned as a String in the following format:

<dataset>
<row>
<Column1>val</Column1>
<Column2>val</Column2>
...
</row>
</dataset>


where the column names are taken from the ResultSet. THIS JAR FILE should be placed in your classpath and then you can call

String s = com.technojeeves.sql.XMLUtils.resultSetToXml(rs);

where 'rs' is your ResultSet.

You can also do

String html = com.technojeeves.sql.XMLUtils.resultSetToHtml(rs);

and get an html table

The jar, containing the source code is also executable, so if you do

java -jar rs2xml.jar

you will get a demo rowset of random data as xml.

import org.jdom.Document;
import org.jdom.Element;

import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;


public class XMLUtils {
    private static String ROOT_NODE_NAME = "dataset";
    private static String ROW_NODE_NAME = "row";

    public static String resultSetToXML(ResultSet rs) {
        String result = null;

        try {
            Document root = new Document(new Element(ROOT_NODE_NAME));
            ResultSetMetaData metaData = rs.getMetaData();

            // Get all rows.
            while (rs.next()) {
                Element row = new Element(ROW_NODE_NAME);
                // Add to root
                root.getRootElement().addContent(row);

                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    // Use the column label as the node name
                    Element val = new Element(metaData.getColumnLabel(i));
                    // Use the String value of the data as the value node's child
                    val.setText("" + rs.getObject(i));
                    row.addContent(val);
                }
            }

            XMLOutputter out = new XMLOutputter();
            out.setFormat(Format.getPrettyFormat());
            result = out.outputString(root);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    // Only for demo/testing
    public static void main(String[] args) throws Exception {
        ResultSet d = new com.technojeeves.sql.DummyNRowCol(4, 10);
        System.out.println(XMLUtils.resultSetToXML(d));
    }
}