Java Reference
In-Depth Information
A much more common application for Xbeans is in converting JDBC ResultSets to XML docume nts, as
illustrated in the next section .
Creating XML Documents by Querying a Database
Creating XML documents from a database is every bit as simple as creating them from a source such
as the system clock. If you refer to the XML document shown in Figure 17-1 , you will notice that it bears
a structural resemblance to a DBMS Table. This is not surprising, since document is derived from one.
There are two basic ways to create XML documents. The first is illustrated in Chapter 15 , where a JSP
is used to extract data from a database and output it as XML in much the same way as JSPs are used
to output HTML. Although this approach produces perfectly valid XML, another, more flexible approach
is to create a DOM representation of the document, which can be processed as desired before
serialization.
An Xbean designed to create DOM documents using SQL queries is shown in Listing 17-7 . The
processDocument() method of this Xbean first creates a DOM document with a root element that
identifies the table name and the database in use. It then calls the method appendDataNodes() ,
which executes the SQL query and appends an element for each row in the ResultSet . The Customer
Number is inserted into this element as an attribute. Nested in each row are elements with tag names
set to the column name and containing the column data as a text node. This example happens to use
the jdbc-odbc bridge driver, but you can easily substitute the DataSource code from any of the
examples in Part III of this topic.
Listing 17-7: Creating an XML document using a SQL query
package JavaDatabaseBible.ch17.Xbeans;
import java.io.*;
import java.sql.*;
import org.Xbeans.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.apache.xerces.dom.DocumentImpl;
/**
* Query a database and return the ResultSet as an XML document
*/
public class SQLQueryBean extends XBean{
private String databaseName = "";
private String tableName = "";
private String SQLQuery = null;
Document document;
public SQLQueryBean(){
}
public void setDatabaseName(String databaseName){
this.databaseName = databaseName;
Search WWH ::




Custom Search