Implement relational database to XML data exchange via Xalan

xiaoxiao2021-03-06  153

content:

Foreword Traditional DB-XML Data Exchange Ways Xalan-Java Developed About SQL XSLT Expansion Details Detailed Xalan, easy to implement relational databases to XML data exchange to build a database environment Compose XSL file Java code design ideas after design ideas Resources and references about the author

There is also a Web service area:

Teaching tools and products all articles

Xue Gu Yu (Rainight@126.com) Nordsan Information Technology Development Co., Ltd. Advanced Java Engineer December 2003

This article describes a solution that divides data acquisition and data conversion into two mutually independent modules, and makes full use of XSLT this emerging technology to bring us convenience, and separate data conversion from Java code, bring to development A new development idea that maximizes software products or projects in relational data to XML data to convert this core process development efficiency.

Foreword Data Exchange is a traditional topic. With the emergence of XML standards in the past two years and is increasingly mature, it will become a core technology that is implemented in various complex heterogeneous data. As a programming language of a pure face-to-objective object of the network, Java is seamless with XML. Since both have a platform-independent, it is the first choice for server-side implementation technology in the field of data exchange. The hardcoding operation of XML data in Java is the current way to develop people, but the complexity and maintenance of the code are very poor. After the design changes in the data exchange format, the code will have a change in the sky, causing the entire entire The inherent instability of the software products and the stagnation of development progress or even reverse. Since XML is a emerging technology, the concept of data exchange is also started in various enterprises worldwide, and the data exchange format has various standards, cross-industry, cross-enterprise data exchange due to the mutual compatibility of data format, is a reason. Very tricky problem. Developers often change the previous code or derive a variety of muds in a data format that is frequently changed by formatting XML formats you can identify from enterprise self-owned systems. The techniques that will be introduced will be described below to divide the data collection and data conversion into two mutually independent modules, and make full use of XSLT this emerging technology to bring us convenience, transfer the data to the Java code from Java code. Bring a new development idea to develop a new idea to maximize software products or projects in relational data to XML data to transform this core process development efficiency. Traditional DB-XML Data Exchange Method About XSLT XSLT is used to convert an XML document into another XML document or another type of document, which is a format that converts an XML document into a browser. One of this is HTML. Typically, XSLT converts each XML element into an HTML element. XSLT can also add new elements to the output file or remove some elements. It can rearrange these elements and classify the elements, test and determine which elements are displayed. One common statement describing this conversion process is that XSL converts an XML source tree into another XML result tree (or converts an XML source document into another XML result document). Little-known cheats -Xalan's convenient database query function Xalan-Java is a set of XSLT processors to convert XML files to other types of file formats such as HTML, Text, and XML. Supports XSLT1.0 and XPath 1.0. Developers can use by command line or in Java Applet and Servlet, and can be used as class libraries for their own applications. Xalan-Java implements the Transformation API for XML (TRAX) interface, which is part of the JAXP1.2 standard. TRAX provides a modular architecture and standard API to perform XML conversion and which converter and XML syntax analyzer uses based on configure settings. Xalan-Java developed about SQL XSLT expansion library Detailed XSLT extension concept When the most basic XSLT syntax does not meet development work, you must develop a set of its own XSLT extension syntax, fortunate is Xalan-Java to let you This idea becomes a reality. The XSLT expansion element and function provide powerful extension features to XSLT processors like Xalan. Apache organizations also provide some expansion support, and we will get more development work on Xalan / Java in Java Open Source enthusiasts, and simplify our development work. Here we mainly introduce the SQL extension of the Xalan-Java comes with. SQL expansion library SQL extension XML namespace is http://xml.apache.org/xalance/SQL, which can be implemented with a JDBC driver to establish a database connection, perform a SQL query and obtain result set. SQL statements for database queries can be given directly in the XSL file or pass the XSL file through the Java program.

The examples in this article use in the latter way, which is more practical. There is also a concept similar to the JDBC in the SQL extension library. "Streamable" result set is the default method of this expansion library acquires the result set. If you use this mode, you can only take a record from the results set, especially, in your style form, the XPath expression will result in unpredictable results in your style form. The core Java class of the extension of SQL libraries is org.apache.xalan.lib.sql.xConnection, which provides all of the features of SQL extensions. The name of Java's function is the name of the SQL extension function function in the XSL file. Here is a few main methods for this class: New (): Establish a database connection through the connection pool. The SQL extension provides a default connection pool implementation, you can also implement your own connection pool through the Java class, which is a more complex technology that is not discussed here. Query (): Perform a query through the database connection, similar to the Connection.executeQuery () enablestreamingmode (): open the stream mode of the record set, only one record is returned at a time. DisablestreamingMode (): Close the stream mode of the record, returns all the records in the result set. Close (): Turn off the database connection, similar to the JDBC's Close () method. The query () function returns a document that contains the description of the result set and the value of each field in the current record in the RESULTSETMETADATA in the JDBC. The above is a simple introduction to the XLAN's SQL extension library from Java's level, which is explained in detail on the specific use of XLST. Create a database connection pool through the Java program: The following code will demonstrate the connection pool of a SQL extension library through the Java program:

// Initialize a connection pool manager

ConnectionPoolManager cpmng = new connectionpoolmanager ();

// Construct a default connection pool

DEFAULTCONNECTIONPOOL CP = New DefaultConnectionPool ();

// Fill in the JDBC driver of the database into the connection pool, here use MySQL's JDBC driver

Cp.SetDriver ("org.gjt.mm.mysql.driver");

// Fill in the URL of the database in the connection pool

CP.SETURL ("JDBC: MySQL: // LocalHost / SPPIX");

// Fill in the connection user name of the database in the connection pool, the user name of this case is root

Cp.setuser ("root");

// Fill in the connection password of the database in the connection pool, the user password of this case is empty.

cp.setpassword ("");

// Set the connection pool

Cp.SetminConnections (10);

/ / Set the open state of the connection pool

cp.setpoolenabled (TRUE);

// Register the connection pool to the connection pool manager

Cpmng.RegisterPool ("SPPIXPool", CP);

Use the connection pool to connect to connect in XSLT

Error Connecting to the Database

We store a database connection with DB, SQL: New () declares that this variable is a database connection; SQL: Connect ($ dB, 'sppoxpool') is created from the database connection pool named SPPXPool, this connection The pool is implemented by the previous Java program; SQL: GetError ($ dB) / ext-error is used to print the error message for the connection database, the content of the error message corresponds to the content in java.sql.sqlexception; SQL: DisablestreamingMode ($ DB) Used to set this connection to non-current mode to return all records in the result set, otherwise only one data record can be returned. In XSLT, the database query first statement declares that a variable name is query, the value of this variable is a SQL statement "Select * from cat", the second statement executes the query and assigns the result of the query to the variable table. Table is a result set variable, corresponding to org.apache.xalan.lib.sql.sqldocument in the Xalan extension library, in the XSLT, the internal levels of the interior can be taken out by XPath. That is called all levels of objects, what objects contain? There is no clear text in the Xalan documentation, but the following is common. SQL is root node element, the following secondary node element is Row-SET, this node is similar to the object of the RESULTSET in the JDBC; the next level of the nodes of the natural row-set is the node element of the ROW, it corresponds to one Database record. You can access this record by XPath, the syntax is

(Note: The $ TABLE variable is defined in the previous section, and the table in the corresponding database is COL, and a field corresponding to a record in each database table. In addition, COL has a method text (), which is the text representation of the value of the value in the Coll. Column-label is a property of column that records the name of the field. It can be taken out by the syntax of @ column-label in XPath. Interrupt the database connection in XSLT

The $ dB is the database connection that has been defined above. The function of this row statement is to disconnect the database after the database connection is used. Driving Xalan, easily implementing the relational database to XML data exchange, detailing the Xalan from the relational database to obtain data, and give a complete and application value example, through it, you will really master this simple Quick data exchange method. This example is simple, which is a table from a name of the relational database named SPPIX, and queries a set of data according to the condition and outputs it to the file according to a specific XML format (of course in truly In the application, this XML data is just an intermediate. With it, you can do any XML operation as you wish. For the reader to facilitate debugging, the relational database in this example uses a popular and free mysql database, and the JDK version is 1.3.1, all class libraries to be used by Java programs in the last "useful resources and reference materials" in this article. Give it. The entire process is completed by a Java program to complete the XSL template file. The process of the Java program is to read the XSL file, pour the query statement in the standard SQL format into the xSL object, and output to the XML file through Xalan. The Java program is responsible for data acquisition, XSL template files responsible for data conversion and presentation. One of this instance code is that the XSL file only needs to be written once. It does not need to be changed, it adapts any query requirements, generates a unified XML format, because the collection of data has been hidden in the java file; on the other hand In the engineering project, the program does not need to care for the generated XML format. When the user or cooperation developer requires changing the XML exchange format, there is no need to change the Java code, simply change the XSL file, you can meet the requirements, great The improved Java code can be reusable, which will increase the work efficiency of the entire development group in the actual work. Java's powerful coupled with Xalan's simple and clear, injecting new vitality into data exchange. Before reading the following chapter, you should have the basic skills of Java accesses the MySQL database through JDBC, and master XML concept and how to manipulate XML through Java and master XPath concept and knowledge. At least at least know what Xalan is doing. If you still feel unfamiliar with Xalan, read the entry information about Xalan. There is no introduction to the basic entry knowledge of the above technology. Building a Database Environment This example creates a database named SPPIX in the MySQL database, establish a table in the database and insert the sample data, as follows: #

# Table structure for table 'cat'

#

Create Table Cat

CAT_ID VARCHAR (32) Not Null Default '0',

Name varchar (16) Not null default ',

Sex char (1) Default Null,

Weight float default null,

PRIMARY Key (CAT_ID)

) TYPE = MyISAM;

#

# DUMPING DATA for TABLE 'CAT'

#

INSERT INTO CAT VALUES ("0001", "small white", "f", "7.4");

INSERT INTO CAT VALUES ("0002", "small black", "m", "7.4");

This table records the basic information of the cat, the meaning of each field is the number of the cat, love, gender (F represents female, M represents male) and weight. Write the file name of the XSL file XSL file named Sample1.xslerror Connecting to the Database

Error in Query

Java code design idea a simple and complete Java implementation code:

Package XMLJDBC;

Import java.io. *;

Import org.apache.xalan.lib.sql.connectionPoolManager;

Import org.apache.xalan.lib.sql.defaultConnectionPool;

Import org.apache.xpath.xpathapi;

Import javax.xml.transform.transformerfactory;

Import javax.xml.transform.transformer;

Import javax.xml.transform.Stream.streamsource;

Import javax.xml.transform.Stream.streamResult;

Import javax.xml.transform.transformerexception;

Import javax.xml.transform.transformerConfigurationException;

Import javax.xml.transform.dom.domsource;

Import org.apache.xml.serializer.writertoutf8;

Public class sample1 {

Public Sample1 () {

}

Public static void main (string [] args) throws exception {

// Initialize a connection pool manager

ConnectionPoolManager cpmng = new connectionpoolmanager ();

// Construct a default connection pool

DEFAULTCONNECTIONPOOL CP = New DefaultConnectionPool ();

// Fill in the JDBC driver of the database into the connection pool, here use MySQL's JDBC driver

Cp.SetDriver ("org.gjt.mm.mysql.driver");

// Fill in the URL of the database in the connection pool

CP.SETURL ("JDBC: MySQL: // LocalHost / SPPIX");

// Fill in the connection user name of the database in the connection pool

Cp.setuser ("root");

// Fill in the connection password of the database into the connection pool

cp.setpassword ("");

// Set the connection pool

Cp.SetminConnections (10);

/ / Set the open state of the connection pool

cp.setpoolenabled (TRUE);

// Register the connection pool to the connection pool manager

Cpmng.RegisterPool ("SPPIXPool", CP);

// parse the XSL file with XML tools

Javax.xml.Parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.NewInstance ();

Javax.xml.parsers.Documentbuilder db = dbf.newdocumentbuilder ();

Org.w3c.dom.document doc = db.parse ("/ Sample1.xsl");

// Replace the value of the path in the XSL file to / stylesheet / param [@ name = "query"] via XPath to replace the value of the node of / stylesheet / param [@ name = "query" org.w3c.dom.node node = xpathapi.selectsinglenode (Doc.getDocumentElement () , "/ stylesheet / param [@Name = //" query // "]");

((org.w3c.dom.element) node) .SetaTRibute ("SELECT", "'SELECT * from cat');

// Create a transformer

TransformerFactory Tfactory = TransformerFactory.newInstance ();

Domsource DOMS = New Domsource (DOC);

Transformer Transformer = TFActory.NewTransformer ();

StringReader Reader =

New stringReader ("

");

StringWriter Writer = new stringwriter ();

/ / Output The modified XSL data flows to StringWriter

Transformer.Transform (DOMS, New StreamResult (Writer);

/ / According to XSL data stream, the XML document is integrated with the result of the database query

Transformer Transformer1 = TFActory.NewTransformer

New StreamSource (New StringReader (Writer.toString ())))))))))

// Output to the XML file name "result.xml"

Transformer1.Transform (New Streamsource (Reader),

New streamResult (New FileoutputStream ("Result.xml"))))

}

}

Run results Generate a file named Result.xml:

0001

noob

Fly

7.4

0002

Small black

M

7.4

After reading this article, you will have a new understanding of XSLT and Xalan, you will say "ah, Xalan can still use this." Yes, if only XSLT is used as an alternative to the HTML era CSS style sheet, control the output of the web page or as a terminal tool that is presented, this idea is too narrow. We should stand on a higher perspective, what kind of revolution can be brought about by emerging technologies to truly give our development methods and development ideas. In the subsequent article, I will introduce other high-end technologies in Xalan, and the technology will never end! Some useful resources and references This document provides all source code in this article, compiles to readers. The latest version of the Xalan toolbase can be downloaded in Apache's official website: http://xml.apache.org/xalan-j/index.html For more content and latest news about XSLT, see http: // www .w3.org / style / XSL / W3C organizations About XSLT extended advice http://www.w3.org/tr/xslt - Extension This article can be used in http://www.mysql.com/ Get free of charge. The JDBC driver of the MySQL database can be downloaded under the URL: http://mysql.ihostunit.com/downloads/contrib/mm.mysql-2.0.4-bin.jar You can refer to XPath's latest specification: Http://www.w3.org/tr/xpath, additionally provide a nice website http://www.zvon.org/xxl/xpathtutorial/general/examples.html, providing XPath tutorials and online connections, let you Easily grasp XPath technology. About author

Xue Guyu is Nordsan (Beijing) Information Technology Development Co., Ltd. Is committed to the development of server products for enterprise-level heterogeneous data exchange. It has a relatively rich development experience in J2EE and Web Service, you can pass Rainight @ 126.com got contact with him.

转载请注明原文地址:https://www.9cbs.com/read-128073.html

New Post(0)