1. Trang chủ
  2. » Công Nghệ Thông Tin

Xml programming bible phần 7 ppt

99 250 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 99
Dung lượng 1,68 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The SQL Server query string uses the CategoryName parameter to complete theSQL query that will be set to the server: String sql = “SELECT dbo.Quotations.Quotation FROM dbo.Quotations INN

Trang 2

position = stringtofix.indexOf (textstring,position+xmlstring.length());

} return stringtofix;

(dbo.Quotations.Quotation = ‘When the hurlyburlys done, When the battles lost and won.’) </sql>

<metadata>

<field name=”Quotation” datatype=”char”/>

<field name=”AuthorName” datatype=”char”/>

<field name=”Source Name” datatype=”char”/>

Trang 3

Next, the result set and the SQL query string are passed to the buildAttributeXMLclass, which is used to build an XML document The buildAttributeXMLclass is shown in Listing 21-13.

Listing 21-12: The GetSingleQuoteAttribute Class

public String GetSingleQuoteAttribute(String PassedQuote) {

String XMLDoc=null;

String sql = “SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name] FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON

dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘“+PassedQuote.trim()+”’)”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”); Connection conn = DriverManager.getConnection

} return XMLDoc ; }

}

Listing 21-13 shows the buildAttributeXML class that is used to create a customelement-based XML document for the SQL Server output It’s very similar to thebuildElementXML class, but this time the code produces row data as attributes

of a single element, instead of nested elements under a records element

Trang 4

The first thing the buildAttributeXML class does is create a new StringBuffer

in which to store the XML document An XML document declaration is sent to theStringBuffer, along with a root element, called resultset Next, an elementcalled sql is created, which contains the SQL Server query that was used to gener-ate the result set We also retrieve the metadata into the XML document, which can

be used by applications that work with the XML document to parse the XML values

by data type and column name We also use the metadata column name to name theelements that represent columns in the XML document

Row data is returned in a single records element Because this example returns asingle row, a single element contains all of the column values as attributes Columnvalues are stored in text data, and column names are represented as elementnames The entityRefs class converts any illegal XML characters in the text data(&, ‘, >, <, and “) into legal entity references for those values

The buildAttributeXMLclass retrieves the XML document from the StringBufferand returns the XML document to the calling object as a string

Listing 21-13: The buildAttributeXML Class

String buildAttributeXML(ResultSet rs, String sql) {

StringBuffer strResults = new StringBuffer(“<?xml version=\”1.0\”

encoding=\”UTF-8\”?>\r\n<resultset>\r\n”);

try { strResults.append(“<sql>” + sql +” </sql>\r\n”);

ResultSetMetaData rsMetadata = rs.getMetaData();

int intFields = rsMetadata.getColumnCount();

strResults.append(“<metadata>\r\n”);

for(int h =1; h <= intFields; h++) { strResults.append(“<field name=\”” + rsMetadata.getColumnName(h) + “\” datatype=\”” + rsMetadata.getColumnTypeName(h) + “\”/>\r\n”);

} strResults.append(“</metadata>\r\n<records>\r\n”);

int rownumber= 0;

while(rs.next()) { rownumber++;

Trang 5

Listing 21-13 (continued)

strResults.append(“/>\r\n”);

} }catch(Exception e) {}

(dbo.Quotations.Quotation = ‘When the hurlyburlys done, When the battles lost and won.’) </sql>

<metadata>

<field name=”Quotation” datatype=”char”/>

<field name=”AuthorName” datatype=”char”/>

<field name=”Source Name” datatype=”char”/>

Trang 6

because of performance, reliability, and compatibility issues Java Applicationsrequire a JDK or a JVM to be loaded on a client’s machine to provide any meaning-ful functionality, and unfortunately share the performance, reliability, and compati-bility characteristics of Java Applets Servlets, however, are a different story JavaServlets are quickly becoming the method of choice for implementing Java solu-tions in enterprise environments, mainly because of the high-performance ServletApplication servers on the market that support high-volume, high-capacity transac-tional Websites Servlets are a natural fit for the middle tiers of multi-tier applica-tion architectures because of their relatively good security model and multi-threadperformance characteristics Because the Java in this case is running exclusively on

a server, there are less performance, distribution, and compatibility issues than theApplet and Java Application Models

Servlets are Java Code that extends the HTTPServlet Java Class, which is the core

of the Sun Java Servlet Development Kit (JSDK) Servlet class files are loaded onto aServlet Application server and are called via Web browser requests Every Servlethas a call method, which receives Servlet requests, and a response, which returnsServlet responses Because of this structure and functionality, Servlets are a greattool for quickly and flexibly generating XML

We will provide some insight into how servlets work in this chapter as we gothrough the sample servlet code, but the chapter will focus more on XML thanservlets If you’re new to servlets and would like more information, the best place

to start is the servlets.com Web page, at http://servlets.com Also, Servlets are aJava Community Process (JCP) Specification The latest Java Specification Request(JSR) document covers the Servlets 2.4 specification, and can be found athttp://web1.jcp.org/en/jsr/detail?id=154

Example: A Three-Tier System Combining Java Applications, Servlets, and SQL Server

In this section we’ll break up the Java Application that we showed you in Listings21-1 to 21-14 and create two multi-tier servlet applications from the pieces

The first application is a Web browser implementation that provides an HTML face to SQL Server data The first tier is a Web browser, which provides the clientuser interface to the data The second tier is made up of four Java Servlets that useJDBC to handle requests for data from the browser and retrieve data from the thirdtier, which is SQL Server and its associated databases The Web application has amore basic user interface than the Java Application The servlets are called viaURLs from a Web page and response data is directed back to a browser windowinstead of a Java Application Object

inter-The second application is a Java Application implementation that provides thesame Swing and AWT interface to SQL Server data as the first application in this

Note

Trang 7

chapter did The difference this time is that the first tier is a Java Application thatonly handles the user interface That means that you don’t need to load MS SQLServer JDBC drivers on the machine that is running the application The JDBCdrivers are used by the four application servlets on the second tier, so they onlyneed to be loaded on the server The third tier is SQL Server.

Prerequisites for Servlet Development

It probably goes without saying that multi-tier applications are harder to developthan single-tier applications The biggest factor is all of the “moving parts.” You usu-ally need a client platform, one or more middle-tier platforms, and a server tier Servlets run on a J2EE application server Examples of J2EE application servers areIBM’s WebSphere application server, Bea WebLogic Application Server, Sun OneApplication Server, and Apache Tomcat You’ll need one of these servers to use theexample servlets in this chapter The servlets need to be deployed onto the J2EEapplication server Many J2EE IDEs come with an integrated J2EE Web applicationserver that makes development, deployment, and testing of servlets much fasterand easier IDES with integrated J2EE servers include IBM’s WebSphere StudioApplication Developer, and the Sun ONE Studio Check your IDE documentation tosee if it provides an integrated J2EE server for servlet development and testing The application and servlets for this example were developed and tested usingIBM’s WebSphere Studio Application Developer (WSAD) 5, which is available as atrial download from http://www7b.software.ibm.com/wsdd/zones/studio WSADincludes an integrated J2EE application server, so servlets can be developed,tested, and deployed on the same machine We are also running Microsoft SQLServer 2000 on the same machine with the JDBC driver loaded

WebSphere Studio Application Developer is discussed in more detail in Chapter 36

Introducing the XML example servlets and client application

The following files are available for download from the XMLProgrammingBible.comWebsite Check with the documentation of your J2EE server for instructions ondeployment and setup Check with your JDK setup instructions for information onrunning the Java client application on a client machine

All the servlets in this example, as well as the Java Application and T-SQL mands for producing the SQL Server data, can be downloaded from theXMLProgrammingBible.com Website, in the Downloads section

com-

Cross-Reference

Trang 8

The Web example application in this chapter uses four servlets:

✦ XMLPBWebServletGetAuthorList gets a list of quote authors from the SQL

Server Authors table

✦ XMLPBWebServletGetSingleAuthorList gets a list of quotes for a single quote

author that a user selects via a URL

✦ XMLPBWebServletBuildElementXML returns a Quote in XML format with

nested elements from row data to a Web browser

✦ XMLPBWebServletBuildAttributeXML returns a Quote in XML format with

attributes created from row data to a Web browser

The multi-tier Java Application uses four servlets and one client application:

✦ XMLPBAppServletGetAuthorList gets a list of quote authors from the SQL

Server Authors table

✦ XMLPBAppServletGetSingleAuthorList gets a list of quotes for a single quote

author that a user selects in the Java Application

✦ XMLPBAppServletBuildElementXML returns a Quote in XML format with

nested elements from row data to the Java Application

✦ XMLPBAppServletBuildAttributeXML returns a Quote in XML format with

attributes created from row data to the Java Application

✦ XMLPBServletApp is a Java Application that calls the above servlets to

retrieve SQL Server data via JDBC

Running the Web Example Application

Once the Web servlets have been deployed on a J2EE server, the MS SQL ServerJDBC driver has been installed, and the JDBC driver is configured to access SQLServer data, start up any browser and open the following URL:

http://<server IP address>/servlet/XMLPBWebServletGetAuthorListMost J2EE application servers are case sensitive URLs must match file name andpath case exactly This is the first thing to check when having trouble with servlets

in a Web browser environment

It may take 10-15 seconds for the Servlet to load the first time due to servlet ization If everything is configured properly, you should get results like those inFigure 21-2 The XMLPBWebServletGetAuthorList Servlet displays a unique list

initial-of quote authors, formatted as URL links

Caution

Trang 9

Figure 21-2: The output for the XMLPBWebServletGetAuthorList servlet, displaying

a list of authors as links

Clicking on one of the links calls the XMLPBWebServletGetSingleAuthorListServlet that generates a list of quotes for a specific author The author is deter-mined by a value that is passed in the link to the servlet The links look like this to aBrowser:

<A HREF=/servlet/XMLPBWebServletGetSingleAuthorList?CategoryName=Dave+Barry

>Dave Barry</A>

Figure 21-3 shows the links for Dave Barry

Under each quote are two links, Element XML to Screen, and Attribute XML

to Screen The Element XML to Screen option calls the XMLPBWebServletBuildElementXMLServlet to return the associated quote in a Custom XMLFormat This is what the link looks like for the first Quote in Figure 21-3:

<A HREF=/servlet/ XMLPBWebServletBuildElementXML?PassedQuote=There+is+a very+fine+line+between+hobby+and+mental+illness.>Element XML to Screen</A>

Trang 10

Figure 21-3: The output for the XMLPBWebServletGetSingleAuthorList Servlet,

displaying a list of quotes for Dave Barry

The Attribute XML to Screen option calls the XMLPBWebServletBuildAttributeXMLServlet to return the associated Quote in another form of customXML format Here’s what this link looks like:

<A HREF=/servlet/ XMLPBWebServletBuildAttributeXML?PassedQuote=There+is+a very+fine+line+between+hobby+and+mental+illness.>Element XML to Screen</A>

Removing spaces from parameters

You may have noticed that the URL parameter references have a + where spacesusually are When a value is passed as a parameter via HTTP, the parser in theapplication that receives the information stops at the first space it encounters,because it is expecting a constant stream of data, and a space indicates the end of avalue Therefore, spaces have to be removed from passed parameters For example,Dave+Barryis received by a servlet as Dave+Barry and the spaces can bereplaced using a simple one-line String.replace method in Java However, DaveBarry(without the +) is parsed as just Dave, and will not match the correct valuewhen re-sent as a parameter to a servlet

Trang 11

Under the Hood of the Web Application Servlets

The four servlets that make up the Web application that retrieves and displaysquotes from SQL Server data are adaptations of the classes that we created for theregular Java Application earlier in this chapter In this section we’ll go under thehood of each servlet to show how they work After that we’ll introduce you to theservlets that are part of the multi-tier Java Application and point out the key differ-ences between the servlets

The XMLPBWebServletGetAuthorList Servlet

The servlet in Listing 21-15 returns a unique listing of quote authors from theAuthors table in the SQL Server XMLProgrammingBible database

Listing 21-15: The XMLPBWebServletGetAuthorList

public class XMLPBWebServletGetAuthorList extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { String [] AuthorList = GetAuthorList();

response.setContentType(“text/html”);

PrintWriter out = response.getWriter();

String title = “A Unique List of Quote Sources”;

out.println(“<HTML><HEAD><TITLE>”+ title +”</TITLE></HEAD>”);

out.println(“<BODY><H1 ALIGN=CENTER>” + title + “</H1>”);

for (int i= 0 ; i < AuthorList.length; i++) { String sl=AuthorList[i].replace(‘ ‘,’+’);

out.print(“<A HREF=/servlet/XMLPBWebServletAppGetSingleAuthorList”);

out.print(“?CategoryName=”+sl+”>”+AuthorList[i]+”</A><br>”); }

Trang 12

out.close();

} public String [] GetAuthorList() { String authorList [] = null;

String sql = “select AuthorName from Authors”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”);

Connection conn = DriverManager.getConnection(“jdbc:microsoft:sqlserver:

} return authorList ; }

String[] buildArray(ResultSet rs) { java.util.List arrayResults = new ArrayList();

try { int rownumber= 0;

String rowvalue = new String();

while(rs.next()) { rownumber++;

rowvalue = rs.getString(rownumber++);

arrayResults.add(rowvalue.trim());

} }catch(Exception e) {}

String[] sarray = (String[]) arrayResults.toArray(new String[arrayResults.size()]);

return sarray;

} }

Trang 13

This servlet starts with standard servlet code constructs A doGet creates therequest and response object that is used to retrieve parameters and return data.The next step is to call the GetAuthorList class, which returns an array of uniquequote authors This is actually just a copy of the array that was used in the previ-ous Java Application example, but this time the class returns data that will be for-matted as HTML

public String [] GetAuthorList() {

For Web browser output, the response.setContentType is set to “text/html.”Next, an instance of the PrintWriter class is created Next, the code generatesHTML to add a Browser window title from the HTML head object, then an HTMLtitle for the Web page

response.setContentType(“text/html”);

PrintWriter out = response.getWriter();

String title = “A Unique List of Quote Sources”;

out.println(“<HTML><HEAD><TITLE>”+ title +”</TITLE></HEAD>”);

out.println(“<BODY><H1 ALIGN=CENTER>” + title + “</H1>”);

Once the basic page layout is set up, The code cycles through the array that wascreated by the GetAuthorList class to generate a URL for each of the uniquequote authors in the array and display the URL as a link on the page Each link callsthe XMLPBWebServletAppGetSingleAuthorList servlet and passes the authordisplayed in the link as a parameter named CategoryName CategoryName isbased on the unique author name It is used to retrieve a list of quotes for thatauthor from the SQL Server Quotations table

for (int i= 0 ; i < AuthorList.length; i++) {

String sl=AuthorList[i].replace(‘ ‘,’+’);

out.print(“<A HREF=/servlet/XMLPBWebServletAppGetSingleAuthorList”);

out.print(“?CategoryName=”+sl+”>”+AuthorList[i]+”</A><br>”);

} out.println(“</BODY></HTML>”);

out.close();

}

The XMLPBWebServletAppGetSingleAuthorList Servlet

The XMLPBWebServletAppGetSingleAuthorList Servlet (Listing 21-16) is calledwhen a user clicks on an Author link from a Web browser The URL that is sent to theServlet passes the CategoryName as a parameter, and returns an array of quotesfor an author back to the Web browser

Trang 14

Listing 21-16: The XMLPBWebServletAppGetSingleAuthorList

public class XMLPBWebServletGetSingleAuthorList extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { String CategoryName=request.getParameter(“CategoryName”);

String [] SingleAuthorList = GetSingleAuthorList(CategoryName);

response.setContentType(“text/html”);

PrintWriter out = response.getWriter();

String title = “Quotes for “+CategoryName.replace(‘+’,’ ‘);

out.println(“<HTML><HEAD><TITLE>”+ title +”</TITLE></HEAD>”);

out.println(“<BODY><H1 ALIGN=CENTER>” + title + “</H1>”);

for (int i= 0 ; i < SingleAuthorList.length; i++) { String sl=SingleAuthorList[i].replace(‘ ‘,’+’);

out.println(“</BODY></HTML>”);

out.close();

}

} public String [] GetSingleAuthorList(String CategoryName) { String singleauthorList [] = null;

Continued

Trang 15

Listing 21-16 (continued)

String sql = “SELECT dbo.Quotations.Quotation FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON dbo.Quotations.SourceID =

dbo.Sources.SourceID WHERE (dbo.Authors.AuthorName =

‘“+CategoryName+”’)”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”); Connection conn =

} return singleauthorList ; }

String[] buildArray(ResultSet rs) { java.util.List arrayResults = new ArrayList();

try { int rownumber= 0;

String rowvalue = new String();

while(rs.next()) { rownumber++;

rowvalue = rs.getString(rownumber++);

arrayResults.add(rowvalue.trim());

} }catch(Exception e) {}

String[] sarray = (String[]) arrayResults.toArray(new String[arrayResults.size()]);

return sarray;

} }

Trang 16

Like the previous servlet, this servlet also returns data to a Web browser as well,but instead of a single link for each quote, this time two links are sent to the screenusing the following code:

for (int i= 0 ; i < SingleAuthorList.length; i++) { String sl=SingleAuthorList[i].replace(‘ ‘,’+’);

If the user clicks on the first link, the XMLPBWebServletBuildElementXML iscalled If the second link is chosen, the XMLPBWebServletBuildAttributeXMLservlet is called Both are passed the PassedQuote parameter, which representsthe actual quote from the Web page The GetSingleAuthorList class is the sameclass that was used in the Java Application earlier in this chapter This class usesthe CategoryName to retrieve all the quotes for that quote source Once the arrayhas been created, it is passed back to the servlet’s doGet to be formatted for theWeb via the PrintWriter Class

The SQL Server query string uses the CategoryName parameter to complete theSQL query that will be set to the server:

String sql = “SELECT dbo.Quotations.Quotation FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON dbo.Quotations.SourceID =

dbo.Sources.SourceID WHERE (dbo.Authors.AuthorName =

‘“+CategoryName+”’)”;

The XMLPBWebServletBuildElementXML Servlet

The code in Listing 21-17 is called when a Quote is selected by clicking on the

“Element XML to Screen” link from a Web browser

Listing 21-17: The XMLPBWebServletBuildElementXML

Trang 17

Listing 21-17 (continued)

import javax.servlet.http.*;

import java.sql.*;

public class XMLPBWebServletBuildElementXML extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { String PassedQuote=request.getParameter(“PassedQuote”);

String XMLQuote = GetSingleQuoteElement(PassedQuote);

String sql = “SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name]

FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘“+PassedQuote+”’)”;

String fromrow=”1”;

String torow=”50”;

String threshold=”50”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”); Connection conn = DriverManager.getConnection

(“jdbc:microsoft:sqlserver://127.0.0.1:1433;

User=jdbcUser;Password=jdbcUser;DatabaseName=XMLProgrammingBible”); Statement s = conn.createStatement();

Trang 18

return XMLDoc ; }

String buildElementXML(ResultSet rs, String sql) { StringBuffer strResults = new StringBuffer(“<?xml version=\”1.0\”

encoding=\”UTF-8\”?>\r\n<resultset>\r\n”);

try { strResults.append(“<sql>” + sql +” </sql>\r\n”);

ResultSetMetaData rsMetadata = rs.getMetaData();

int intFields = rsMetadata.getColumnCount();

strResults.append(“<metadata>\r\n”);

for(int h =1; h <= intFields; h++) { strResults.append(“<field name=\”” + rsMetadata.getColumnName(h) + “\” datatype=\”” + rsMetadata.getColumnTypeName(h) + “\”/>\r\n”);

} strResults.append(“</metadata>\r\n<records>\r\n”);

int rownumber= 0;

while(rs.next()) { rownumber++;

strResults.append(“<record rownumber=\””+rownumber+”\”>\r\n”);

for(int i =1; i <= intFields; i++) { strResults.append(“<” + rsMetadata.getColumnName(i) +

“>” + entityRefs(rs.getString(i).trim()) +

“</”+rsMetadata.getColumnName(i) +”>\r\n”);

} strResults.append(“</record>\r\n”);

} }catch(Exception e) {}

strResults.append(“</records>\r\n</resultset>”);

System.out.println(strResults.toString());

return strResults.toString();

} String entityRefs(String XMLString) { String[] before = {“&”,”\’”,”>”,”<”,”\””};

String[] after = {“&amp;”,”&apos;”,”&gt;”,”&lt;”,”&quot;”};

if(XMLString!=null) { for(int i=0;i<before.length;i++) { XMLString = stringReplace(XMLString, before[i], after[i]);

} }else {XMLString=””;}

return XMLString;

}

Continued

Trang 19

position = stringtofix.indexOf(textstring,position+xmlstring.length());

} return stringtofix;

} }

This time the output is not HTML The output is formatted as XML for display onthe Web browser screen Consequently, the Web output option is much simplerthan the previous two examples The content type to text/xml instead of the pre-vious type, text/html Once this is done the string that was generated by theGetSingleQuoteElementclass is retrieved and returned to the Web as a string

a structure of nested XML elements for each row of data in the result set

The XMLPBWebServletBuildAttributeXML Servlet

The code in Listing 21-18 is called when a quote is selected by clicking on the

“Attribute XML to Screen” link from a Web browser As in the previous example, theoutput it text formatted as XML, so the content type is set to “text/xml.” Once this

is done, a string is generated by the buildAttributeXML class The new string isreturned to the Web as an XML document

The buildAttributeXML, entityRefs, and stringReplace classes are copies

of the classes with the same name from the previous Java example Once the XMLoutput string has been created, it is passed back to the servlet’s doGet to be for-matted for the Web via the PrintWriter class

Trang 20

Listing 21-18: The XMLPBWebServletBuildAttributeXML Code

public class XMLPBWebServletBuildAttributeXML extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { String PassedQuote=request.getParameter(“PassedQuote”);

String XMLQuote = GetSingleQuoteAttribute(PassedQuote);

response.setContentType(“text/xml”);

PrintWriter out = response.getWriter();

out.println(“<?xml version=\”1.0\” encoding=\”UTF-8\” ?>”);

out.println(XMLQuote);

out.close();

} public String GetSingleQuoteAttribute(String PassedQuote) { String XMLDoc=null;

String sql = “SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name] FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON

dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘“+PassedQuote.trim()+”’)”;

String fromrow=”1”;

String torow=”50”;

String threshold=”50”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”);

Connection conn = DriverManager.getConnection (“jdbc:microsoft:sqlserver://127.0.0.1:1433;

User=jdbcUser;Password=jdbcUser;

DatabaseName=XMLProgrammingBible”);

Statement s = conn.createStatement();

Continued

Trang 21

} return XMLDoc ; }

String buildAttributeXML(ResultSet rs, String sql) { StringBuffer strResults = new StringBuffer(“<?xml version=\”1.0\” encoding=\”UTF-8\”?>\r\n<resultset>\r\n”);

try { strResults.append(“<sql>” + sql +” </sql>\r\n”);

ResultSetMetaData rsMetadata = rs.getMetaData();

int intFields = rsMetadata.getColumnCount();

strResults.append(“<metadata>\r\n”);

for(int h =1; h <= intFields; h++) { strResults.append(“<field name=\”” + rsMetadata.getColumnName(h) + “\” datatype=\”” + rsMetadata.getColumnTypeName(h) + “\”/>\r\n”);

} strResults.append(“</metadata>\r\n<records>\r\n”);

int rownumber= 0;

while(rs.next()) { rownumber++;

strResults.append(“<record rownumber=\””+rownumber+”\””); for(int i =1; i <= intFields; i++) {

strResults.append(“ “+rsMetadata.getColumnName(i) + “ =

\”” + entityRefs(rs.getString(i).trim()) + “\””); }

strResults.append(“/>\r\n”);

} }catch(Exception e) {}

strResults.append(“</records>\r\n</resultset>”);

System.out.println(strResults.toString());

return strResults.toString();

}

Trang 22

String entityRefs(String XMLString) { String[] before = {“&”,”\’”,”>”,”<”,”\””};

String[] after = {“&amp;”,”&apos;”,”&gt;”,”&lt;”,”&quot;”};

if(XMLString!=null) { for(int i=0;i<before.length;i++) { XMLString = stringReplace(XMLString, before[i], after[i]);

} }else {XMLString=””;}

return XMLString;

} String stringReplace(String stringtofix, String textstring, String xmlstring) {

int position = stringtofix.indexOf(textstring);

while (position > -1) { stringtofix = stringtofix.substring(0,position) + xmlstring + stringtofix.substring(position+textstring.length());

position = stringtofix.indexOf(textstring,position+

xmlstring.length());

} return stringtofix;

} }

A Multi-Tier Java Application

The second set of servlets that you were introduced to earlier in this chapter workwith a Java Application instead of a Web browser This Java Application example inthis chapter is based on the first Java Application example that I showed you ear-lier in this chapter It has been adapted as a multi-tier system by adding the ability

to call servlets from the application, instead of containing all of the applicationcode and functionality on the server This eliminates many of the client configura-tion headaches associated with loading extra support classes on the clientmachine, such as JDBC drivers It also provides more control over the data that isaccessed, because the SQL queries are stored on the server It also provides reme-dial security by moving much of the access and processing of data away from theuser and onto a server

Installing the XMLPBServletApp Java Application

The XMLPBServletApp.java application has to be installed in a directory of a station that is accessible to the Java JDK on the same machine, and accessible tothe server that is running the servlets over a network Once the application is

Trang 23

work-downloaded, run the application by typing java XMLPBServletApp from a mand prompt or the Windows “Run “ menu option The application will appear onthe screen in its own Java window The application is identical in function to thesingle-tier Java Application shown earlier in this chapter It’s what’s happeningbehind the scenes that is probably of more interest to developers In this sectionwe’ll show you how the servlets interact with the Java Application and SQL Server.

com-Under the Hood of the Multi-Tier Application Servlets

The Java Application and four servlets that make up the Quote XML Generator –Servlet Edition Application are adaptations of the classes that we created for theregular single-tier Java Application that we showed earlier in this chapter In thissection we’ll go under the hood of each servlet and the application to show howthey work together

The XMLPBAppServletGetAuthorList Servlet

The code in Listing 21-19 is a servlet that returns a unique listing of authors to aJava Application The buildArray class is a coy of the buildArray class in thesingle-tier Java Application

Listing 21-19: The XMLPBAppServletGetAuthorList

public class XMLPBAppServletGetAuthorList extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

String [] AuthorList = GetAuthorList();

Trang 24

response.setContentType(“application/x-java-serialized-ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());

Connection conn = DriverManager.getConnection(

} return authorList ; }

String[] buildArray(ResultSet rs) { java.util.List arrayResults = new ArrayList();

try { int rownumber= 0;

String rowvalue = new String();

while(rs.next()) { rownumber++;

rowvalue = rs.getString(rownumber++);

arrayResults.add(rowvalue.trim());

} }catch(Exception e) {}

String[] sarray = (String[]) arrayResults.toArray(new String[arrayResults.size()]);

return sarray;

}

Trang 25

Instead of preparing the response object to return text for Web output, theXMLPBAppServletGetAuthorListservlet returns an object to the calling appli-cation that matches the original data format specified in the application Theresponse.setContentTypeis set to application/x-java-serialized-object, which is a mime type that can support any serializable Java class Servletsthat access the Java Application are passing arrays and strings back to the applica-tion, so this format is perfect for the needs of this application A new instance of theObjectOutputStreamis created, which in an extension of the Java Stream class,instead of a PrintWriter or other type of Writer implementation The callingapplication uses an ObjectInputStream on the other end, which I will cover inmore detail later in the chapter Next, the code simply writes the AuthorList tothe ObjectOutputStream, which is an array that was created by the

GetAuthorListclass

object”);

response.setContentType(“application/x-java-serialized-ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());

out.writeObject(AuthorList);

out.flush();

The XMLPBAppServletGetSingleAuthorList Servlet

The XMLPBAppServletGetSingleAuthorList Servlet in Listing 21-20 iscalled when a user clicks on an author name in the Java Application The call that

is sent to the Servlet passes the CategoryName as a parameter and returns anarray of quotes for the selected author If the Servlet is being called from a JavaApplication, the array representing the quote for a single author is passed tothe ObjectOutputStream The ObjectOutputStream is passed back to theservlet’s doGet and then is sent back to the Java Application as an array via theObjectOutputStreamclass

Listing 21-20: The XMLPBAppServletGetSingleAuthorList

public class XMLPBAppServletGetSingleAuthorList extends HttpServlet {

public void doGet(HttpServletRequest request,

Trang 26

HttpServletResponse response) throws IOException, ServletException { String CategoryName=request.getParameter(“CategoryName”);

String [] SingleAuthorList = GetSingleAuthorList(CategoryName);

object”);

response.setContentType(“application/x-java-serialized-ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());

out.writeObject(SingleAuthorList);

out.flush();

} public String [] GetSingleAuthorList(String CategoryName) { String singleauthorList [] = null;

String sql = “SELECT dbo.Quotations.Quotation FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID =

dbo.Authors.AuthorID INNER JOIN dbo.Sources ON dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Authors.AuthorName = ‘“+CategoryName+”’)”;

String fromrow=”1”;

String torow=”50”;

String threshold=”50”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”);

Connection conn = DriverManager.getConnection(“jdbc:microsoft:sqlserver://

} return singleauthorList ; }

Continued

Trang 27

Listing 21-20 (continued)

String[] buildArray(ResultSet rs) { java.util.List arrayResults = new ArrayList();

try { int rownumber= 0;

String rowvalue = new String();

while(rs.next()) { rownumber++;

rowvalue = rs.getString(rownumber++);

arrayResults.add(rowvalue.trim());

} }catch(Exception e) {}

String[] sarray = (String[]) arrayResults.toArray(new String[arrayResults.size()]);

return sarray;

} }

The XMLPBAppServletBuildElementXML Servlet

The code in Listing 21-21 is called when a quote is selected by choosing theElement XML (Table=Root, Field Name=Element)option as the quote out-put format in the Java Application The content type we set to text/xml, indicat-ing that an XML document is being built as the servlet output The string

representing the Single Quote in XML Format is passed from the GetSingleQuoteElementclass to the ObjectOutputStream via the servlet’s doGet Rows

of data are formatted as nested elements in the XML document structure SQLServer column names become XML document element names, and column valuesbecome text data values

Listing 21-21: The XMLPBAppServletBuildElementXML

Trang 28

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { String PassedQuote=request.getParameter(“PassedQuote”);

String XMLQuote = GetSingleQuoteElement(PassedQuote);

String sql = “SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name] FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON

dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘“+PassedQuote+”’)”;

String fromrow=”1”;

String torow=”50”;

String threshold=”50”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”);

Connection conn = DriverManager.getConnection(“jdbc:microsoft:sqlserver://

} return XMLDoc ; }

Continued

Trang 29

Listing 21-21 (continued)

String buildElementXML(ResultSet rs, String sql) { StringBuffer strResults = new StringBuffer(“<?xml version=\”1.0\” encoding=\”UTF-8\”?>\r\n<resultset>\r\n”);

try { strResults.append(“<sql>” + sql +” </sql>\r\n”);

ResultSetMetaData rsMetadata = rs.getMetaData();

int intFields = rsMetadata.getColumnCount();

strResults.append(“<metadata>\r\n”);

for(int h =1; h <= intFields; h++) { strResults.append(“<field name=\”” + rsMetadata.getColumnName(h) + “\” datatype=\”” + rsMetadata.getColumnTypeName(h) + “\”/>\r\n”);

} strResults.append(“</metadata>\r\n<records>\r\n”);

int rownumber= 0;

while(rs.next()) { rownumber++;

strResults.append(“<record rownumber=\””+rownumber+”\”>\r\n”);

for(int i =1; i <= intFields; i++) { strResults.append(“<” + rsMetadata.getColumnName(i) +

“>” + entityRefs(rs.getString(i).trim()) +

“</”+rsMetadata.getColumnName(i) +”>\r\n”);

} strResults.append(“</record>\r\n”);

} }catch(Exception e) {}

strResults.append(“</records>\r\n</resultset>”);

System.out.println(strResults.toString());

return strResults.toString();

} String entityRefs(String XMLString) { String[] before = {“&”,”\’”,”>”,”<”,”\””};

String[] after = {“&amp;”,”&apos;”,”&gt;”,”&lt;”,”&quot;”}; if(XMLString!=null) {

for(int i=0;i<before.length;i++) { XMLString = stringReplace(XMLString, before[i], after[i]); }

}else {XMLString=””;}

return XMLString;

} String stringReplace(String stringtofix, String textstring, String xmlstring) {

Trang 30

while (position > -1) { stringtofix = stringtofix.substring(0,position) + xmlstring + stringtofix.substring(position+textstring.length());

position = stringtofix.indexOf(textstring,position+xmlstring.length());

} return stringtofix;

} }

The XMLPBAppServletBuildAttributeXML Servlet

The code in Listing 21-22 is called when a quote is selected by choosing theAttribute XML (Table=Element, Field Name=Attribute)option as thequote output format in the Java Application As with the last example, the contenttype is set to text/xml, indicating that an XML document is being built as theservlet output The string representing the Single Quote in XML Format is passedfrom the GetSingleQuoteAttribute class to the ObjectOutputStream via theservlet’s doGet Rows of data are formatted as attributes in a row element in theXML document structure SQL Server column names become XML documentattribute names, and column values become attribute values

Listing 21-22: The XMLPBAppServletBuildAttributeXML

public class XMLPBAppServletBuildAttributeXML extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { String PassedQuote=request.getParameter(“PassedQuote”);

String XMLQuote = GetSingleQuoteAttribute(PassedQuote);

response.setContentType(“application/x-java-serialized-object”);

Continued

Trang 31

String sql = “SELECT dbo.Quotations.Quotation, dbo.Authors.AuthorName, dbo.Sources.[Source Name] FROM dbo.Quotations INNER JOIN dbo.Authors ON dbo.Quotations.AuthorID = dbo.Authors.AuthorID INNER JOIN dbo.Sources ON

dbo.Quotations.SourceID = dbo.Sources.SourceID WHERE (dbo.Quotations.Quotation = ‘“+PassedQuote.trim()+”’)”;

String fromrow=”1”;

String torow=”50”;

String threshold=”50”;

try { Class.forName(“com.microsoft.jdbc.sqlserver.SQLServerDriver”); Connection conn =

} return XMLDoc ; }

String buildAttributeXML(ResultSet rs, String sql) { StringBuffer strResults = new StringBuffer(“<?xml version=\”1.0\” encoding=\”UTF-8\”?>\r\n<resultset>\r\n”);

try { strResults.append(“<sql>” + sql +” </sql>\r\n”);

ResultSetMetaData rsMetadata = rs.getMetaData();

int intFields = rsMetadata.getColumnCount();

Trang 32

for(int h =1; h <= intFields; h++) { strResults.append(“<field name=\”” + rsMetadata.getColumnName(h) + “\” datatype=\”” + rsMetadata.getColumnTypeName(h) + “\”/>\r\n”);

} strResults.append(“</metadata>\r\n<records>\r\n”);

int rownumber= 0;

while(rs.next()) { rownumber++;

} }catch(Exception e) {}

strResults.append(“</records>\r\n</resultset>”);

System.out.println(strResults.toString());

return strResults.toString();

} String entityRefs(String XMLString) { String[] before = {“&”,”\’”,”>”,”<”,”\””};

String[] after = {“&amp;”,”&apos;”,”&gt;”,”&lt;”,”&quot;”};

if(XMLString!=null) { for(int i=0;i<before.length;i++) { XMLString = stringReplace(XMLString, before[i], after[i]);

} }else {XMLString=””;}

return XMLString;

} String stringReplace(String stringtofix, String textstring, String xmlstring) {

int position = stringtofix.indexOf(textstring);

while (position > -1) { stringtofix = stringtofix.substring(0,position) + xmlstring + stringtofix.substring(position+textstring.length());

position = stringtofix.indexOf(textstring,position+xmlstring.length());

} return stringtofix;

} }

Trang 33

Under the Hood of the XML Quote Generator — Servlet Edition Application

The Java Application in this example is based on the single-tier Java Applicationthat was shown earlier in this chapter There are only a few changes that need to bemade to the original Java Application to adapt it for use a multi-tier applicationclient The main change is to remove all of the classes that are not located in theservlets The other change is to adapt the classes that called those classes to callservlets instead Listing 21-23 shows the changed code in the XMLPBServletAppJava Application

I can now remove the java.sql.* import for the SQL Server JDBC driver classes,because all JDBC driver functionality has been moved to the servlets This meansthat the application can be loaded on any workstation that supports Java JDK 1.3.1

or higher, and does not have to have a JDBC driver or any other external supportpackages installed The second change is the addition of a variable at the top of theapplication that specifies the server location and the directory on that serverwhere the servlets are located

Listing 21-23: Changed Code in the XMLPBServletApp Java

String ServletURLBase = “http://127.0.0.1/servlet/”;

In addition to the two small changes to the application code, there are a fewchanges to the classes Instead of containing code that generated lists of authors,

Trang 34

quotes, and XML output in the Application code, the classes are now used to callservlets that pass the correct data back to the application in the required format.

Listing 21-24 shows the classes that have been changed in the XMLPBServletAppJava Application:

Listing 21-24: Changed Classes in the XMLPBServletApp Java

Application

public String [] GetAuthorList() {

String AuthorList [] = null;

try{

ObjectInputStream inputFromServlet = null;

String ServletCall = ServletURLBase +

“XMLPBAppServletGetAuthorList”;

URL ServletURL = new URL( ServletCall );

URLConnection ServletConnection = ServletURL.openConnection();

inputFromServlet = new ObjectInputStream(ServletConnection.getInputStream());

AuthorList = (String []) inputFromServlet.readObject();

} catch(Exception e) { e.printStackTrace();

} return AuthorList ; }

public String [] GetSingleAuthorList(String CategoryName) { String singleAuthorList [] = null;

try{

ObjectInputStream inputFromServlet = null;

String ServletCall = ServletURLBase +

“XMLPBAppServletGetSingleAuthorList”;

ServletCall += “&CategoryName=”+CategoryName.replace(‘ ‘,’+’);

URL ServletURL = new URL( ServletCall );

URLConnection ServletConnection = ServletURL.openConnection();

inputFromServlet = new ObjectInputStream(ServletConnection.getInputStream());

singleAuthorList = (String []) inputFromServlet.readObject();

} catch(Exception e) { e.printStackTrace();

}

Continued

Trang 35

Listing 21-24 (continued)

return singleAuthorList ; }

public String GetSingleQuoteElement(String PassedQuote) { String XMLDoc=null;

try{

ObjectInputStream inputFromServlet = null;

String ServletCall = ServletURLBase +

“XMLPBAppServletBuildElementXML”;

ServletCall += “&PassedQuote=”+PassedQuote.replace(‘ ‘,’+’); URL ServletURL = new URL( ServletCall );

URLConnection ServletConnection = ServletURL.openConnection(); inputFromServlet = new

ObjectInputStream(ServletConnection.getInputStream());

XMLDoc = (String) inputFromServlet.readObject();

} catch(Exception e) { e.printStackTrace();

}

return XMLDoc ; }

public String GetSingleQuoteAttribute(String PassedQuote) { String XMLDoc=null;

try{

ObjectInputStream inputFromServlet = null;

String ServletCall = ServletURLBase +

“XMLPBAppServletBuildAttributeXML”;

ServletCall += “&PassedQuote=”+PassedQuote.replace(‘ ‘,’+’); URL ServletURL = new URL( ServletCall );

URLConnection ServletConnection = ServletURL.openConnection(); inputFromServlet = new

ObjectInputStream(ServletConnection.getInputStream());

XMLDoc = (String) inputFromServlet.readObject();

} catch(Exception e) { e.printStackTrace();

}

Trang 36

return XMLDoc ; }

Each class in the Java Application builds a URL that calls the appropriate servletand creates a ObjectInputStream to receive data from the ObjectOutputStreamthat is generated by the servlet Below is the code that retrieves the list authorsfrom the Authors table in the SQL Server XMLProgrammingBible database:

ObjectInputStream inputFromServlet = null;

String ServletCall = ServletURLBase +

“XMLPBAppServletGetAuthorList”;

URL ServletURL = new URL( ServletCall );

URLConnection ServletConnection = ServletURL.openConnection();

inputFromServlet = new ObjectInputStream(ServletConnection.getInputStream());

AuthorList = (String []) inputFromServlet.readObject();

In this example, a new instance of the ObjectInputStream is created, and aURL is assembled into a string using the ServletURLBase variable assigned

at the beginning of the application, the servlet name, and any appropriateparameters that need to be passed to the servlet Next a URL object is createdfrom the string, and a URLConnection is created using the newly created URLand the openConnection() method This calls the servlet, which returns anObjectOuputStream The ObjectInputStream on the application sidecollects the response from the servlet and passes the response back to theapplication The response from the servlet that has been collected using theObjectInputStreamis assigned to an object in the Java Application viathe ObjectInputStream.readObject method There are two formats forresponses from the servlets in this application: arrays and strings An arraythat contains a list of authors is received using this code:

AuthorList = (String []) inputFromServlet.readObject();

A Java string that contains custom XML for a single quote is received using thiscode:

XMLDoc = (String) inputFromServlet.readObject();

In either case, the object is passed back to the application and used as an element

of the application user interface

Trang 37

In this chapter we’ve outlined techniques for building J2EE applications that workwith XML documents and relational data:

✦ A J2EE sample application

✦ Using JDBC with J2EE applications that use JDBC

✦ Controlling custom XML formats

✦ A three-tier system combining Java Applications, servlets, and JDBC

✦ Accessing servlets from a Web browser

✦ Accessing servlets from a J2EE application

In the next chapter we’ll show you how to transform relational data from oneRDBMS format to another using XSL, and relational XML data formats

Trang 38

Transforming Relational

XML Output into Other Formats

So far in this section we’ve shown you how to get XML

data out of MS SQL Server, Oracle, and DB2 You can usethe generated XML to integrate data with other formats ofXML using XSLT transformation You can also transform therelational XML output directly to HTML, or load the data into

an XML data island

In this chapter we’ll review XSL transformation of XML tional data formats that we showed you in Chapters 18, 19,and 20 for MS SQL Server, Oracle, and DB2 We’ll start with acomparison of each vendor’s approach to transforming XML

rela-Then we’ll show you how to transform data structures fromeach RDBMS platform We include examples of stylesheets fortransforming XML output from MS SQL Server, Oracle andDB2 These can serve as good bases for your own transforma-tion stylesheets

We’ll also show you a way to transform a generalized XML mat created by the JDBC-based J2EE application that weshowed you in Chapter 21 During the process we’ll puttogether a framework for transforming relational data formats,including tips for converting relational XML output to HTML

for-We’ll finish up the chapter with an XML data islands examplethat transforms relational data and manipulates the data in aWeb browser client using Microsoft XML Core Services(MSXML)

22C H A P T E R

In This Chapter

Options fortransformingrelational XML dataXSL stylesheets fortransformingrelational dataTransformationfunctions in Oracle,DB2, and MS SQLServer

Transforming JDBCresult sets to HTMLUsing MSXML withrelational dataCreating data islandsfrom relational XML

Trang 39

In this chapter we’ll cover the ways of formatting relational data as XML, but

we won’t cover the fundamentals of XSLT For that information, refer to Chapters 7and 8

Transformation Functions in Oracle, DB2, and MS SQL Server

Each RDBMS vendor has its own way of handling XSL transformations, either viaSQL functions, or via other languages that receive XML output from the RDBMS.Major software vendors are providing facilities for developers to generate HTMLdirectly to a Web browser using XSLT While this may be a handy feature for devel-opers, it’s a potential security nightmare for RDBMS administrators Allowing directaccess between a Web browser and a relational database is not a recommendedsolution for most secure IT shops

We’ll show you the easiest ways to generate HTML from relational data via XSLtransformations, but flexible application architectures should always use a middle-tier HTTP server such as MS Internet information Server (IIS), a portal server such

as IBM WebSphere portal server, an MS SharePoint server, or a J2EE applicationserver The middle tier takes some of the processing load from the RDBMS serverand also acts as a physical and virtual security layer The middle tier of a multi-tierapplication separates the Web from your data store That’s a good thing, as Marthawould say

Later in the chapter we’ll show you an example of transforming JDBC XML outputfrom the J2EE application in Chapter 21 Because this technique can be used in amulti-tier environment, it may be a more appropriate solution than directly produc-ing HTML from relational data

When creating XSL stylesheets to transform relational output to HTML, don’t hurtyourself by trying hand-code and test stylesheet Use an XSLT tool like the XMLSpystylesheet designer, which is available as a trial download from http://www.XMLSpy.com We used it to create all of the examples in this chapter Othertools are available from www.xmlsoftware.com, but we’ve found the XMLSpyStylesheet designer to be the best, if not the cheapest

MS SQL Server and XSL

There are two ways to transform data in SQL Server output An XSL stylesheet can

be included in a template file as a default stylesheet Any XML document outputthat is created with this template is automatically transformed by a SQL Server

Tip Note

Trang 40

before results are sent back to the requestor You can also specify a stylesheet viaURI when making a URL call to a template file

For more information on working with XML in SQL Server, please refer to Chapter 19

Transforming MS SQL Server XML results with an XSL stylesheet

SQL Server 2000 supports two ways to automatically transform XML results using

an XSL stylesheet In this example, the ResultTransform.xsl stylesheet isstored in the stylesheets subdirectory of the IIS virtual directory This is not anofficial directory for stylesheets, just a directory that we chose to create and storestylesheets in It could be contained anywhere under the virtual directory and benamed anything The relative path reference branches from the virtual directoryroot

You can also reference stylesheets inside a template file using the sql:xslattribute of a template’s root tag Here’s an example of a very simple query thattransforms a row of XML data to HTML:

If a template contains an XSL stylesheet reference and a stylesheet is specified

in a URL that calls the template, stylesheet in the URL overrides the templatestylesheet reference

Transforming FOR XML AUTO output to HTML

Here’s the output that is generated by the example template shown above TheQueryRootroot element is defined in the temple, everything else is created by theSQL command The row that is retuned is defined by a single element calledAmazonListings, and all of the columns in that row are defined by an attributewith the format columnName=”value” Note that the ampersands (&) in thetagged_URLattribute have been converted to entity references (&amp;) This ispart of the functionality of the AUTO SQL command parameter

Note Cross-

Reference

Ngày đăng: 09/08/2014, 18:22

TỪ KHÓA LIÊN QUAN