Creating Authors.xml from Table
Last Modified On : 25-july-2005
// program to create authors.xml from AUTHORS table
import javax.xml.parsers.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.sql.*;
public class CreateAuthors {
public static void main(String[] argv) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document;
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
// connect to database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:authors","Admin","");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from authors");
Element authors,author,ele;
authors = document.createElement("authors");
document.appendChild(authors);
while ( rs.next())
{
author = document.createElement("author");
ele = document.createElement("au_id");
ele.appendChild(document.createTextNode(rs.getString("au_id")));
author.appendChild(ele);
ele = document.createElement("author");
ele.appendChild(document.createTextNode(rs.getString("author")));
author.appendChild(ele);
ele = document.createElement("yearborn");
ele.appendChild(document.createTextNode(rs.getString("yearborn")));
author.appendChild(ele);
authors.appendChild(author);
}
rs.close();
st.close();
con.close();
FileWriter fw = new FileWriter("authors.xml");
// Use a Transformer for output
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(fw);
transformer.transform(source, result);
} // main
}