Created
September 18, 2013 20:04
-
-
Save kelvinewilliams/6614814 to your computer and use it in GitHub Desktop.
Reusable class for generating DOM from a ResultSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.kelvinwilliams.utils | |
import org.w3c.dom.Document; | |
import org.w3c.dom.Element; | |
import javax.xml.parsers.DocumentBuilder; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import javax.xml.parsers.ParserConfigurationException; | |
import java.sql.ResultSet; | |
import java.sql.ResultSetMetaData; | |
import java.sql.SQLException; | |
/** | |
* Created with IntelliJ IDEA. | |
* <p/> | |
* User: k | |
* Date: 9/18/13 | |
* Time: 2:06 PM | |
*/ | |
public class Reports { | |
public Reports() {} | |
public Document getXml(ResultSet resultSet) { | |
Document document = null; | |
try { | |
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); | |
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); | |
document = documentBuilder.newDocument(); | |
Element responseElement = document.createElement("response"); | |
document.appendChild(responseElement); | |
ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); | |
int resColumns = resultSetMetaData.getColumnCount(); | |
while (resultSet.next()) { | |
Element recordElement = document.createElement("record"); | |
responseElement.appendChild(recordElement); | |
for (int c = 1; c <= resColumns; c++) { | |
String colName = resultSetMetaData.getColumnName(c); | |
Object colValue = resultSet.getObject(c); | |
Element colElement = document.createElement(colName); | |
colElement.appendChild(document.createTextNode(colValue.toString())); | |
recordElement.appendChild(colElement); | |
} | |
} | |
} catch (ParserConfigurationException e) { | |
e.printStackTrace(); | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} | |
return document; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment