Use XML and XSL to generate dynamic pages

Source: Internet
Author: User
Tags xml parser blank page
This article explains in detail how xml (Extensible Markup Language) may look like a w3c standard-there is no practical impact now, even if it can be used in the future, it will be a long time later. Xml (Extensible Markup Language) may look like a w3c standard-there is no real impact now, even if it can be used in the future, it will be a long time later. But in fact, it is now applied. Therefore, do not use xml until it has been added to your favorite html editor. It can now solve various internal and B2B system problems.

In sparks.com, we use xml to standardize data representation between different systems, such as java objects and html data display.

In particular, we found that data can be shared and operated more easily as long as the standard is implemented with a very basic xml structure. In this process, we found many effective methods to use xml. The following describes our current application in detail.

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

Generate Dynamic xml
Generating html from a database is not new, but generating xml is fresh. Here we will introduce the specific generation steps.

Using xsl as the template language
Xsl (extensible style sheet language) is a good way to define the xml data display format. it is more effective if you write several static templates.

Generate html
Adding xsl to xml is equivalent to html. This sounds wrong, but what we see in the user's html page is actually the result of the combination of xml and xsl.

I. standardization

The xml capability comes from its flexibility. But unfortunately, it is sometimes too flexible, so 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. Therefore, you must make the following decisions:

• Data to be involved
• Whether to use dtd (file type definition)
• Whether to use dom (Document Object Model) or sax (simplified xml api) for parsing

Confirm data:
Because there is no standard xml format, developers can develop their own formats freely. However, if your format can only be recognized by one application, you can only run this program to use this format. If there are other programs that can read your xml format, it is obviously more helpful. If an xml format is modified, the system that uses it may also need to be modified. Therefore, you should establish a complete format as much as possible. Because most systems ignore tags that they cannot recognize, the safest way to change an xml format is to add tags instead of modifying tags.

Click here to view the xml data format instance

At sparks.com, we checked all the product data required for different products. Although not all pages use all data, we have developed a very complete xml data format for all data. For example, our product details 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 only uses the fields it requires.

Whether to use dtd
In sparks.com, we use well-organized xml, not just the correct xml, because the former does not require dtd. The dtd adds a processing layer between the user clicks and the page that appears. We found that this layer requires too much processing. Of course, when you communicate with other companies in xml format, using dtd is quite good. Because dtd can ensure that the data structure is correct when sending and receiving data.

Select resolution engine
Currently, there are several parsing engines available. Which one to choose depends almost entirely on your application needs. If you decide to use dtd, this parsing engine must make your xml validated by dtd. You can put the verification in another process, but that will affect the performance.

Sax and dom are two basic parsing models. The event is sent to the engine when the xml is parsed based on the event. Next, the event is synchronized with the output file. The dom parsing engine creates 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 determined by the xsl style sheet. The debate on the sax model mainly focuses on the reduction of memory in the dom structure and the shortening of the time for parsing the xsl style table.

However, we found that many systems using sax did not fully utilize its capabilities. These systems use it to create a dom structure and send events through the dom structure. In this way, dom must be created from the style sheet before any xml processing, so the performance will decrease.

II. generate Dynamic xml

Once the xml format is set up, we need a way to dynamically port it from the database.

Generating an xml document is relatively simple because it only requires a system that can process strings. We have built a system that uses java servlet, enterPRise javabean server, jdbc, and rdbms (relational database management system.

• Servlet processes product information requests by handing over 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 servlet.
• Servlet calls the parsing engine to create html output from xml files and static xsl style sheets.

(For more information about xsl applications, see using xsl as the template language .)

Example 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 generation process is put in the ejb method. This routine 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 () variables are calls to other methods.
Generate a file header
The first additional method calls the xmlutils class to generate an 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("
 \n")    .append("
 \n");   xml.append("<").append(page).append(">\n");   return xml.tostring(); }

This code generates an xml file header. 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 table used to display data. Finally, it includes the item-level label (in this instance ). At the end of the file, only The tag must be disabled.

Enter Product Information
After the file header is completed, the control method calls the java Object to generate its xml. In this example, the product object is called. The product object uses two methods to generate its xml representation. The first method toxml () is generated And Label to create a product node. It then calls internalxml () to provide the content required for the product xml. Internalxml () is a series of stringbuffer. append () calls. Stringbuffer is also converted to a string and returned to the control method.

Public string toxml () {stringbuffer xml = new stringbuffer ("
 
  
\ N "); xml. append (internalxml (); xml. append ("
 \ 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"); begin? 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"; success? Return xml. tostring ();}

Close File
Finally, the xmlutils. enddocument () method is called. This call closes the xml tag (in this example) and finally completes the xml file with a good architecture. The entire stringbuffer from the control method is also converted to a string and returned to the servlet that processes the original http request.

III. using xsl as the template language

To get html output, we combine the generated xml file with the xsl template that controls how xml data is represented. Our xsl template consists of carefully organized xsl and html tags.

Start template creation
The beginning part of our xsl template is similar to the following code. The first line of code is required. This file is defined as an xsl style sheet. Xmlns: xsl = attribute references the xml namespace used in this file, while version = attribute defines the version number of the namespace. Close the tag at the end of the file.

By The second line of code at the beginning confirms the xsl template mode. The match attribute is required and points to the xml tag here. . In our system, Tag contains Label, which makes the xsl template accessible The product information in the tag. Once again, we must close it at the end of the file. Label.

Next, let's take a look at the well-organized html. Because it will be processed by the xml parsing engine, it must comply with all the well-organized xml rules. Essentially, this means that all start labels must have corresponding end labels. For example

Tag, required

Disable.

 
  
   shopping bag / adjust quantity 
   
?br>

Many xsl labels are used in the template body to provide logic for data representation. The following describes two commonly used labels.
Choose
Labels are similar to the starting part of the if-then-else structure in traditional programming languages. In xsl, the choose label indicates that the assignment will trigger the action in the code entry section. With the value assignment attribute The tag follows the choose tag. If the value assignment is correct The content between the start tag and the end tag is used. If the value assignment is incorrect, use Between the start and end labels. For the whole part .

In this example, the when tag checks the xml for the quantity tag. If the quantity tag contains the error attribute whose value is true, the quantity tag displays the table units listed below. If the attribute value is not true, xsl displays the content between otherwise labels. In the following example, if the error attribute is not true, nothing will be displayed.

 
  
   *not enough in stock. your quantity was adjusted accordingly. 
  
   
  
 

For-each
Tags can be used to apply the same style sheet to multiple situations of similar xml data. For us, we can retrieve a series of product information from the database and format it on the web page. Here is an example:

 
  
 

The for-each loop starts when the program encounters a tag. This loop ends when the program encounters a tag. Once this loop is run, this template will be applied every time the tag appears.

4. generate html

In the future, the browser will integrate the xml parsing engine. At that time, you can directly send xml and xsl files to the browser, while the browser displays xml data according to the rules listed in the style sheet. However, before that, developers will have to create parsing functions in their server-side systems.

At sparks.com, we have integrated an xml parser in java servlet. This parser uses a mechanism called xslt (xsl transformation) to add xml data to the xsl template according to the description of the xsl tag.

When our java servlet processes http requests, the servlet retrieves the dynamically generated xml and then transmits the xml to the parsing engine. Based on the instructions in the xml file, the parsing engine looks for the appropriate xsl style sheet. The parser creates an html file through the dom structure, and then transmits the file to the user who sends the http request.

If you choose to use the sax model, the parser will read the xml source program and create an event for each xml tag. The event corresponds to the xml data, and finally inserts data into the style sheet according to the xsl tag.

The above section uses XML and XSL to generate dynamic page content. For more information, see PHP Chinese website (www.php1.cn )!

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.