Sparks.com uses XML and XSL to generate dynamic pages

Source: Internet
Author: User
Tags add end header object model string version tostring trim
xml| Dynamic | page XML (Extensible Markup Language) it might look like some sort of a world standard--there's no real impact right now, even if it comes in handy later. But in fact, it has now been applied. So don't wait until the XML has been added to your favorite HTML editor to start using it. It can now solve a variety of internal problems and business-to-business systems issues.

In sparks.com, we use XML to standardize data representations between different systems, from Java objects to HTML data displays.

In particular, we find that it is easier to share and manipulate data as long as it is standardized with a very basic XML structure. In this process, we have found many effective ways to use XML. Here is a detailed description of our current application.

Standardization
Before using XML, create an XML data format that is different from the information you want to use.

Generating dynamic XML
Generating HTML from a database is not new, but generating XML is new. Here we describe the specific build steps.

Using XSL as the template language
XSL (Extensible Stylesheet Language) is a good way to define the format of XML data display, which is more efficient if you write several static templates.

Generate HTML
XML plus xsl equals HTML. This may not sound right, but what the user sees in our HTML pages is actually the effect of XML and XSL together.


First, standardization

The ability of XML comes from its flexibility. Unfortunately, it is sometimes so flexible that you will face a blank page and worry about how to solve the problem.

In any XML project, the first step is to create a standard data format. To do this you have to make the following decision:

• What data to involve
• Do you want to use a DTD (file type definition)
• Do you want to use the DOM (Document Object model) or sax (XML's simplified API) to parse

Determine the data:
Because there is no standard XML format, developers are free to develop their own formats. However, if your format can only be identified by one application, you can only run this program to use that format. If there are other programs that can read your XML format, it's obviously more helpful. If an XML format is modified, the system that uses it may also need to be modified, so you should create as complete a format as possible. Because most systems ignore tags they don't recognize, the safest way to change an XML format is to add tags instead of modifying them.

Click here to view XML data format instances

At Sparks.com, we looked at all the product data needed for different product presentations. Although not all pages use all of the data, we have developed a very complete XML data format for all the data. For example, our Product detail page displays more data than the Product browsing page. However, we still use the same data format in both cases, because each page's XSL template uses only the fields it needs.

Whether to use DTDs
In sparks.com, we use well-formed XML instead of just the right XML because the former does not require a DTD. The DTD adds a layer of processing between the user clicks and sees the page. We find that this layer requires too much processing. Of course, using DTDs is good when communicating with other companies in XML format. Because DTDs can be sent and accepted to ensure that the data structure is correct.

Select the resolution engine
Now, there are several parsing engines that you can use. Which one you choose depends almost entirely on your application needs. If you decide to use a DTD, then the parsing engine must be able to validate your XML with DTDs. You can put the validation in one process, but that will affect performance.

Sax and Dom are two basic parsing models. Sax is based on events, so when XML is parsed, events are sent to the engine. Next, the event synchronizes with the output file. The DOM parsing engine establishes a hierarchical tree structure for dynamic XML data and XSL style sheets. By randomly accessing the DOM tree, you can provide XML data, just as it would be determined by an XSL style sheet. The controversy over the SAX model focuses on the reduction of memory over the DOM structure and the shortening of the XSL Stylesheet parsing time.

However, we find that many systems using sax do not fully develop their capabilities. These systems use it to create a DOM structure and send events through the DOM structure. In this way, the DOM must be built from the style sheet before any XML processing, so performance can degrade.

Second, generate dynamic XML

Once the XML format is established, we need a way to migrate it from the database dynamically.

Generating an XML document is relatively straightforward because it only requires a system that can handle strings. We built a system that uses Java Servlet, Enterprise JavaBean Server, JDBC, and RDBMS (relational database management system).

servlet processes product Information requests by handing the task of generating XML documents to Enterprise JavaBean (EJB).
EJB uses JDBC to query the required product details from the database.
EJB generates an XML file and passes it to the servlet.
Servlet calls the parsing engine to create HTML output from XML files and static XSL style sheets.

(For additional information about XSL applications, see Using XSL as the template language.) )

Examples of generating XML
The real code for creating XML document strings in Java can be divided into several methods and classes.

The code that starts the XML build process is placed in the EJB method. This instance immediately creates a stringbuffer to store the generated XML string.

StringBuffer XML = new StringBuffer ();
Xml.append (Xmlutils.begindocument ("/browse_find/browse.xsl", "Browse", request));
Xml.append (Product.toxml ());
Xml.append (xmlutils.enddocument ("browse");
Out.print (Xml.tostring ());


The next three xml.append () variable itself is a call to other methods.
Generate File Headers
The first additional method calls the Xmlutils class to produce the XML file header. The code in our Java servlet is as follows:

public static string Begindocument (String stylesheet, String page)
{
StringBuffer XML = new StringBuffer ();
Xml.append ("<?xml version=\" 1.0\ ">\n")
. Append ("<?xml-stylesheet href=\")
. Append (Stylesheet). Append ("\")
. Append ("type =\" text/xsl\ "? >\n");
Xml.append ("<"). Append (page). Append (">\n");
return xml.tostring ();
}

This code generates the XML file header. <?xml> label defines this file as an XML file that supports version 1.0. The second line of code points to the location of the correct style sheet to display the data. Finally, the item level tag (<browse> in this case) is included. At the end of the file, only the <browse> label needs to be closed.

<?xml version= "1.0"?> <?xml-stylesheet href= "/browse_find/browse.xsl" type= "text/xsl"?> <browse>

Fill in the Product information
When the file header is finished, the control method invokes the Java object to produce its XML. The Product object is called in this example. The Product object uses two methods to produce its XML representation. The first method ToXml () creates the product node by generating the <product> and </product> tags. It then invokes Internalxml (), which provides the content required for the product XML. Internalxml () is a series of stringbuffer.append () calls. The StringBuffer is also converted to a string and returned to the control method.
Public String toXml ()
{
StringBuffer XML = new StringBuffer ("<product>\n");
Xml.append (Internalxml ());
Xml.append ("</product>\n");
return xml.tostring ();
}

Public String Internalxml ()
{
StringBuffer XML = new
StringBuffer ("T")
. Append (ProductType). Append ("\ n");
Xml.append ("T"). Append (Idvalue.trim ())
. append ("\ n");
Xml.append ("T"). Append (Idname.trim ())
. append ("\ n");
Xml.append ("T"). Append (Page.trim ())
. append ("\ n");
厖?
Xml.append ("\ T"). Append (Amount). append ("\ n");
Xml.append ("\ T"). Append (Vendor). Append ("\ n");
Xml.append ("\t\n");
Xml.append ("\ T"). Append (Pubdesc). Append ("\ n");
Xml.append ("\ T"). Append (Vendesc). Append ("\ n";
厖?
return xml.tostring ();
}


Close File
Finally, the Xmlutils.enddocument () method is invoked. This call closes the XML tag (in this case) and eventually completes the schema-ready XML file. The entire stringbuffer from the control method is also converted to a string and returned to the servlet that handles the original HTTP request.

Iii. using XSL as template language

To get the HTML output, we combine the generated XML file with the XSL template that controls how XML data is represented. Our XSL templates are made up of carefully organized XSL and HTML tags.

Start building a template
The beginning of our XSL template is similar to the following piece of code. The first line of code is the required code, which defines this file as an XSL style sheet. The Xmlns:xsl= property refers to the XML namespace used in this file, while the Version= property defines the version number of the namespace. At the end of the file, we close the label.

The second line of code, starting with <xsl:template>, determines the pattern of the XSL template. The match attribute is required, pointing to the XML tag <basketPage>. In our system, the,<basketpage> tag contains <product> tags, which allows the XSL template to access product information embedded in the <product> tag. Once again we must close the <xsl:template> tag at the end of the file.

Next, let's look at the well-organized HTML. Because it will be processed by the XML parsing engine, it must conform to all the rules of well-formed XML. Essentially, this means that all the start tags must have a corresponding closing tag. For example, a <P> label that is not normally closed must be closed with </P>.


<xsl:stylesheet xmlns:xsl= "Http://www.w3.org/1999/XSL/Transform"
Version= "1.0" >
<xsl:template match= "Basketpage" >
<title>shopping Bag/adjust quantity</title>
<body bgcolor= "#cccc99" bgproperties= "fixed" link= "#990000" vlink= "#990000" >
<br>
?br> </xsl:template>
</xsl:stylesheet>


Within the body of the template, there are many XSL tags that are used to provide logic for the data representation. The following explains two commonly used labels.
Choose
<xsl:choose> tags are similar to the beginning of if-then-else structures in traditional programming languages. In XSL, the Choose tag represents the part in which the code enters, and the assignment triggers the occurrence of the action. The <xsl:when> tag with the assigned property is followed by the Choose Tag. If the assignment is correct, the content between the start and end tags of <xsl:when> is used. If an assignment error occurs, the content between the start and end tags of <xsl:otherwise> is used. The whole section ends with </xsl:choose>.

In this case, the when tag checks the XML for the quantity tag. If the quantity tag contains an error property with the value True, the quantity tag will display the table cell listed below. If the value of the property is not true, the XSL displays the content between the otherwise tags. In the following example, if the error property is not true, nothing is displayed.

<xsl:choose>
<xsl:when test= "quantity[@error = ' true ']" >
&LT;TD bgcolor= "#ffffff" ></td>
&LT;TD valign= "Top" bgcolor= "#ffffff" colspan= "2" ><font face= "Verdana, Arial" size= "1" color= "#cc3300" ><b >*not enough in the stock. Your Quantity was adjusted accordingly.</b></font></td>
</xsl:when>
<xsl:otherwise>
</xsl:otherwise>
</xsl:choose>


For-each
<xsl:for-each> tags can be used to apply the same style sheet to a variety of scenarios for similar XML data. For us, you can take a series of product information from the database and make a unified format on the Web page. Here's an example:
<xsl:for-each select= "Package" >
<xsl:apply-templates select= "Product"/>
</xsl:for-each>


The For-each loop starts when the program encounters a label. This loop ends when the program encounters a label. Once the loop runs, the template is applied every time the label appears.

Iv. Generate HTML

At some point in the future, the browser will integrate the XML parsing engine. By then, you can send XML and XSL files directly to the browser, while the browser displays the XML data according to the rules listed in the stylesheet. Before that, however, developers will have to create parsing functions on their server-side systems.

In sparks.com, we have integrated an XML parser into the Java servlet. The parser uses a mechanism called XSLT (XSL Transformation) to add XML data to the XSL template as described in the XSL label.

When our Java Servlet handles HTTP requests, the servlet retrieves the dynamically generated XML, and then the XML is passed to the parsing engine. Depending on the instructions in the XML file, the parsing engine looks for the appropriate XSL style sheet. The parser creates an HTML file from the DOM structure, which is then transmitted to the user who issued the HTTP request.

If you choose to use the SAX model, the parser will read through the XML source program and create an event for each XML tag. The event corresponds to the XML data and eventually inserts the data into the style sheet by the XSL label.



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.