| ResultSet to XML |
|
|
|
| Written by Charles | |||||
| Friday, 31 October 2008 18:18 | |||||
|
This class is a utility to turn a Java ResultSet into xml. It's returned as a String in the following format: <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 = net.proteanit.sql.XMLUtils.resultSetToXml(rs); where 'rs' is your ResultSet. You can also do String html = net.proteanit.sql.XMLUtils.resultSetToHtml(rs); and get an html table The jar is a 'fat jar', as it uses JDOM. It's also executable, so if you do java -jar rs2xml.jar you will get a demo rowset of random data. 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 net.proteanit.sql.DummyNRowCol(4, 10); System.out.println(XMLUtils.resultSetToXML(d)); } }
Only registered users can write comments!
Powered by !JoomlaComment 3.26
3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved." |
|||||
| Last Updated ( Thursday, 10 November 2011 23:59 ) |



