Using DOM and XSL to format data extracted by Java

Source: Internet
Author: User
Tags abstract format define odbc sql string format version oracle database
dom| data Java extracts data from any JDBC-compliant database, converts the data into a DOM object, and then formats the data into the desired form using XSL. In the previous article, we demonstrated how to programmatically extract data from a database. Now, let's talk about how to build a DOM object and format the data with an XSL style sheet. As a result, the final output is available to any application as long as you provide them with the input you need.



Building a DOM document


The latest version of Java supports JAXP XML processing and implements the DOM API defined by the World Wide Web Consortium (WWW). Using these compliant versions, you can create a DOM document object with just 3 lines of code, using the Jaxp factory and builder methods:


Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Documentbuilder builder = Factory.newdocumentbuilder ();
Document document = Builder.newdocument ();

We create a root element named ResultSet and add it to the Document object


Element root = document.createelement ("resultset");
Document.appendchild (root);

When the ResultSet cursor traverses the result set, a new element containing the row data is added to the root element:


Element NextRow = document.createelement ("row");

The column count must be read from the ResultSetMetaData object, and it must be defined in the database data extraction phase of this project:

int columnCount = Rsmd.getcolumncount ();

The column name is retrieved with a for loop, and a name node is added for each column name, with a textnode containing the name value for a names element:


string[] ColumnNames = new String[columncount];
Element names = document.createelement ("names");
for (int i = 0; I〈columncount i++) {
/* The 1, the second is 2, ... * *
Columnnames[i] = rsmd.getcolumnname (i + 1);
Element Nextnamenode = document.createelement ("name");
Text nextname = document.createTextNode (Columnnames[i]);
Nextnamenode.appendchild (Nextname);
Names.appendchild (Nextnamenode);
}

The column index starts at 1 rather than 0. When reading each row of data, the column values are frequently retrieved as strings in a for loop, and the For loop reads each column value:



/* Move the cursor through the "Data one row at a" time. */
while (Resultset.next ()) {
/* Create a Element node for each row of data. */
Element NextRow = document.createelement ("row");
if (Debug) System.out.println ("New Row");
for (int i = 0; I〈columncount i++) {
/* Create an Element node for each column value. */
Element NextNode = document.createelement (Columnnames[i]);
/* The 1, the second is 2, ... * *
/* GetString () would retrieve any of the basic SQL types*/
Text text = document.createTextNode (resultset.getstring (i + 1));
Nextnode.appendchild (text);
Nextrow.appendchild (NextNode);
}
Root.appendchild (NextRow);
}

After all data has been converted to a DOM document object, the connection can be closed. Databasehandler never need to do file operations. The XML document was created in memory.
A specific Databasehandler object


With a few lines of code, you can construct a generalized defaultdatabasehandler:



public class Defaultdatabasehandler extends abstractdatabasehandler{

Public Defaultdatabasehandler (String urlstring, String userName,
string password, string drivername) {

Seturlstring (urlstring);
Setusername (UserName);
SetPassword (password);
Setdrivername (drivername);
}
}

The Oracledatabase handler is a little bit complicated:

public class Oracledatabasehandler extends abstractdatabasehandler{

Private String Thinoracleprefix = "jdbc:oracle:thin:@";
Private String urlstring;
Private String UserName;
private String password;
Private String drivername = "Oracle.jdbc.OracleDriver";
Private String host;
Private String Port;
Private String SID;

Public Oracledatabasehandler (string host, String Sid,
String userName, string password) {

This.host = host;
This.sid = SID;
/* A valid URL connection string format is: "Host:port:sid" * *
Seturlstring (Thinoracleprefix + host + ": 1521:" + SID);
Setusername (UserName);
SetPassword (password);
}

Public Oracledatabasehandler (string host, string port, String sid,
String userName, string password) {

This.host = host;
This.sid = SID;
This.port = port;
/* A valid URL connection string format is: "Host:port:sid" * *
Seturlstring (Thinoracleprefix + host + ":" + Port + ":" + SID);
Setusername (UserName);
SetPassword (password);
}
}

Odbcdatabasehandler is not very different, except that it handles data source names (DSNs) rather than host names, ports, and SIDS. The reason to use the host name, port number, and SID associated with the Oracle database is that we are dealing with a database server, not a database file. However, the Microsoft access relational database uses the. mdb file:

public class Odbcdatabasehandler extends abstractdatabasehandler{

Private String urlstring;
Private String UserName;
private String password;
Private String drivername = "Sun.jdbc.odbc.JdbcOdbcDriver";
Private String DSN;
Private String ODBCPrefix = "JDBC:ODBC:";
Public Odbcdatabasehandler (String DSN, String userName, string password) {
/* A valid URL connection string format is: "JDBC:ODBC:DSN" * *
THIS.DSN = DSN;
Seturlstring (ODBCPrefix + DSN);
Setusername (UserName);
SetPassword (password);
Setdrivername (drivername);
}
}

To learn the details of accessing a particular database, consult your product documentation. You need to use another class to invoke a specific databasehandler and make XSL transformations to convert the database results into a useful alternative output type.
Sqlmapper

The Sqlmapper class uses a Databasehandler class to complete its database work and uses a mapping method to convert the document object to the desired output type. The mapping method returns a string because the output is assumed to be composed of character data. Alternatively, you can use a stringbuffer.

Sqlmapper requires an SQL query string, an output type set, and a databasehandler to perform the specific work. They are initialized with the set method and retrieved using the Get method:




if ((GetSQL ()!= null)
&& (GetSQL (). Length () 〉0)
&& (Getoutputtype ()!= null)
&& (Isvalidoutputtype (Getoutputtype ())
&& (Getdatabasehandler ()!= null)) {
Document document = Databasehandler.getdocument (GetSQL ());

To convert to the desired output, you need to specify an XSL style sheet in the Set method. We created a Transformer object that only provides a private Gettransformer method. This method gets either a default style sheet or a specified style sheet. If necessary, you can use the Java Transformerfactory method to generate a style sheet:



Transformerfactorytransformerfactory = Transformerfactory.newinstance ();
Transformer = Transformerfactory.newtransformer (Getstylesheet ());

Just a few lines of Java code to complete the conversion:


Transformer Transformer = Gettransformer ();
STRINGWRITERSW = new StringWriter ();
Streamresult result = new Streamresult (SW);
if (transformer!= null) {
Transformer.transform (New Domsource (Document.getdocumentelement ()), result);
Output = Sw.tostring ();
System.err.println ("Output:" + output);
}else{
System.err.println ("No Transformer");
}

The transformer object requires a Domsource object. To get this object, we pass the root element of a DOM document to the Transformer constructor.

Finally, the implementation will design its own XSL style sheet. You can also use a few default style sheets to convert raw data to HTML or XML. The following is a generalized XSL stylesheet that uses the so-called identity transformation technology to transform the generated data into an XML document and to ensure that the output is compatible with the UTF-8 standard and is well readable.

〈?xml version= "1.0" encoding= "UTF-8"?
〈xsl:stylesheet xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform" version= "1.0"
〈xsl:output method= "xml" version= "1.0" encoding= "UTF-8" indent= "yes"/〉
〈xsl:template match= "@*|node ()"
〈xsl:copy〉
〈xsl:apply-templates select= "@*|node ()"/〉
〈/xsl:copy〉
〈/xsl:template〉
〈/xsl:stylesheet〉


The following is a generalized XSL stylesheet that converts the generated data into an HTML table:




〈?xml version= "1.0" encoding= "UTF-8"?
〈xsl:stylesheet xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform" version= "1.0"
〈xsl:output method= "html" indent= "yes"/〉

〈xsl:template match= "ResultSet"
〈H2 align= "center" 〉default HTML Transform result〈/h2〉
〈table border= "1" align= "center" 〉〈xsl:apply-templates/〉〈/table〉
〈/xsl:template〉
〈xsl:template match= "Names"
〈tr〉〈xsl:apply-templates/〉〈/tr〉
〈/xsl:template〉
〈xsl:template match= "Name"
〈td〉〈xsl:apply-templates/〉〈/td〉
〈/xsl:template〉
〈xsl:template match= "Row"
〈tr〉〈xsl:apply-templates/〉〈/tr〉
〈/xsl:template〉
〈xsl:template match= "*"
〈td〉〈xsl:apply-templates/〉〈/td〉
〈/xsl:template〉

〈/xsl:stylesheet〉

The following is a generalized XSL style sheet that converts the generated data into a WML (Wireless Markup Language) Table:


〈?xml version= "1.0" encoding= "UTF-8"?
〈xsl:stylesheet xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform" version= "1.0"
〈xsl:output method= "html" indent= "yes"/〉
〈xsl:template match= "ResultSet"
〈wml〉
〈card id= "index" title= "Default WML Transform Result"
〈xsl:apply-templates/〉〈/card〉
〈/wml〉
〈/xsl:template〉
〈xsl:template match= "Names"
names:〈xsl:apply-templates/〉
〈/xsl:template〉
〈xsl:template match= "Name"
〈i〉〈xsl:apply-templates/〉〈/i〉
〈/xsl:template〉
〈xsl:template match= "Row"
〈card〉〈xsl:apply-templates/〉〈/card〉
〈/xsl:template〉
〈xsl:template match= "*"
〈i〉〈xsl:apply-templates/〉〈/i〉
〈/xsl:template〉

〈/xsl:stylesheet〉

The following is a generalized XSL stylesheet that converts the generated data into a comma-separated table (CSV table), which can be read directly in Excel:



〈?xml version= "1.0" encoding= "UTF-8"?
〈xsl:stylesheet xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform" version= "1.0"
〈xsl:output method= "text" indent= "yes"/〉
〈xsl:template match= "Names"
〈xsl:for-each select= "*"
〈xsl:if test= "position ()!= last ()" 〉〈xsl:value-of select= ". /〉,〈/xsl:if〉
〈xsl:if test= "position () = Last ()" 〉〈xsl:value-of select= ". /〉〈/xsl:if〉
〈/xsl:for-each〉
〈/xsl:template〉
〈xsl:template match= "Row"
〈xsl:for-each select= "*"
〈xsl:if test= "position ()!= last ()" 〉〈xsl:value-of select= ". /〉,〈/xsl:if〉
〈xsl:if test= "position () = Last ()" 〉〈xsl:value-of select= ". /〉〈/xsl:if〉
〈/xsl:for-each〉
〈/xsl:template〉
〈/xsl:stylesheet〉

Some ideas of using sqlmapper


The back-end database can use a table to define the form elements of the Web page user interface. In a JSP page, you can retrieve the table in just a few lines of code. Your Web server may have an Oracle database installed, but there is no front-end graphical user interface. You can now define the elements of a GUI to make the database work:


〈%@ page language= "java" contenttype= "text/html" import= "sqlmapper.*, mywebapp.*%〉
〈%@ page errorpage= "errorpage.jsp"%〉
〈html〉
!--getuserarea.jsp executed on〈%= (new Java.util.Date ())%〉--〉
!--@Author: Charles Bell--〉
!--@Version: April 22, 2003--〉
〈head〉
〈title〉your Company name-〈%= Dynamictitle%〉〈/title〉
〈/head〉
〈body background= "〈%= dynamicbackgroundimagefilename%〉"
〈%
webapputilitymywebapputility = new Webapputility ();
String host = Mywebapputility.getdatabasehost ();
String sid = Mywebapputility.getdatabasesid ();
String userName = (string) session.getattribute ("Validatedusername");;
String password = Mywebapputility.getdatabasepassord ();
Sqlmapper mapper = new Sqlmapper ();
Databasehandler databasehandler=
New Oracledatabasehandler (host, sid, UserName, password);

Mapper.setsql ("SELECT * from formdataelements");
Mapper.setoutputtype ("HTML");
Mapper.setdatabasehandler (Databasehandler);
Mapper.setxsltranformstylesheet ("stylesheets/formdata.xsl");
Out (MAPPER.MAP);
%〉
〈% @include file= "footer.jsp"%〉
〈/body〉
〈/html〉

With these techniques, just click a button and the JSP page pops up the latest report that is dynamically generated based on an active database. The CSV output can be used to generate dynamic Excel spreadsheets. The XML output provides services to another Web application that communicates with its own back-end database.


Summary

We described how to create an interface to define the Databasehandler generalization behavior and implement it with an abstract class to extend this abstract class into a custom, concrete database handler, all with just a few lines of Java code. The Sqlmapper class uses this behavior to transparently connect a relational database, execute a SQL query, and convert the data into a DOM document object. The transformation of a DOM object is then accomplished by applying an XSL stylesheet to obtain the desired output. The output can then be used by any application, using an efficient, easy to implement way to provide the input you need.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.