Home >Backend Development >XML/RSS Tutorial >Use XML and XSL to generate dynamic pages

Use XML and XSL to generate dynamic pages

黄舟
黄舟Original
2017-03-30 17:11:131341browse

xml (Extensible Markup Language) may look like some kind of w3c standard - it has no real impact now, and even if it does come in handy later, it will be a long time later. But in fact, it is already being used. So, don't wait until XML is added to your favorite HTML editor to start using it. It can solve various internal problems and b2b system problems now.

At sparks.com, we use xml to standardize data representation between different systems, from java objects to html data displays.

In particular, we found that by standardizing on a very basic xml structure, it is easier to share and manipulate data. In the process, we discovered many effective ways 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. Here we introduce the specific generation steps.

Use xsl as template language
XSL (Extensible Stylesheet Language) is a good way to define the XML data display format. It will be more effective if it is written as several static templates.

Generate html
xml plus xsl equals html. This may not sound right, but our html page that users see is actually the result of xml and xsl.

1. Standardization

The ability of xml comes from its flexibility. But unfortunately, it's sometimes so flexible that you're left with a blank page wondering how to solve the problem.

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

• Which data to involve
• Whether to use dtd (file type definition)
• Whether to use dom ( Document Object Model) or SAX (simplified API for XML) parsing

Determine the data:
Because there is no standard XML format, developers are free to develop their own formats. However, if your format is only recognized by one application, then you can only run that application to use the format. It would obviously be more helpful if there were other programs that could also read your xml format. If an XML format is modified, the system using it may also need to be modified, so you should build the format as complete as possible. Because most systems ignore tags they don't recognize, the safest way to change the format of an XML is to add tags, not modify them.

Click here to view xml data format example

At sparks.com, we have looked at all the product data needed for different product displays. Although not all pages use all data, we have developed a very complete xml data format suitable for all data. For example, our product details page displays more data than our product browse page. However, we still use the same data format in both cases because each page's xsl template only uses the fields it needs.

Whether to use dtd
At sparks.com, we use well-organized xml rather than just correct xml, because the former does not require dtd. DTD adds a layer of processing between the user clicking and seeing the page. We found this layer required too much processing. Of course, it's still nice to use DTDs when communicating with other companies in XML format. Because dtd can ensure that the data structure is correct when sending and receiving.

Select parsing engine
Now, there are several parsing engines that can be used. Which one you choose depends almost entirely on your application needs. If you decide to use DTD, then the parsing engine must be able to enable your XML to be verified by DTD. You could put the validation into a separate process, but that would impact performance.

sax and dom are two basic parsing models. SAX is event based, so when the xml is parsed, events are sent to the engine. Next, the events are synchronized 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, XML data can be provided as if determined by an XSL stylesheet. The debate on the SAX model mainly focuses on excessive memory reduction of the DOM structure and speeding up the parsing time of the XSL style sheet.

However, we found that many systems using sax did not fully utilize its capabilities. These systems use it to build DOM structures and send events through DOM structures. With this approach, the DOM must be built from the stylesheet before any XML processing, so performance will suffer.

2. Generate dynamic xml

Once the xml format is established, we need a method that can dynamically transplant it from the database.

Generating xml documents is relatively simple because it only requires a system that can handle strings. We built a system using java servlet, enterPRise javabean server, jdbc and rdbms (relational database management system).

• The servlet handles product information requests by offloading the task of generating xml documents to enterprise javabean (ejb).
• ejb uses jdbc to query the required product details from the database.
• ejb generates the xml file and passes it to the servlet.
• The servlet calls the parsing engine to create html output from xml files and static xsl style sheets.

(For additional information on the application of methods and classes.

The code to start the xml generation process is placed in the ejb method. This instance will immediately create 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 following three xml.append() variables themselves are calls to other methods.

Generate file header

The first additional method calls the xmlutils class to generate 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. The 8a82eb472d64dd53782fcc091813a312 tag 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. The last thing included is the item-level tag (86d47457b1f44f493b73b959a822e430 in this example). At the end of the file, only the 86d47457b1f44f493b73b959a822e430 tag needs to be closed.

dc55d8f1b8d0d15e8e0c4fca7640a4b5 0a338bad3442b76cc533181ca2a63f24 86d47457b1f44f493b73b959a822e430

Fill in product information

After completing the file header, the control method will call 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() creates the product node by generating a719999c5224e00a42ab5e276e57a41b and 1da18c4b98da1fc43a8786f07f99713f tags. It then calls internalxml(), which provides the required content 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 the file
Finally, the xmlutils.enddocument() method is called. This call closes the xml tag (in this case) and finally completes the structured xml file. The entire stringbuffer from the control method is also converted to a string and returned to the servlet that handled the original http request.

3. Use xsl as template language

In order to get html output, we combine the generated xml file with the xsl template that controls how the xml data is represented. Our xsl templates consist of carefully organized xsl and html tags.

Start building the template

The beginning of our xsl template is similar to the following code. The first line of code is required and defines this file as an xsl style sheet. The xmlns:xsl= attribute refers to the xml namespace used by this file, and the version= attribute defines the version number of the namespace. At the end of the file we close the tag.

The second line of code starting with 2032d1f3e843089f381a035edc734156 determines the mode of the xsl template. The match attribute is required and here points to the xml tag 34ab9008638189d20e962c822c883981. In our system, the 34ab9008638189d20e962c822c883981 tag contains the a719999c5224e00a42ab5e276e57a41b tag, which allows the xsl template to access the product information embedded in the a719999c5224e00a42ab5e276e57a41b tag. Once again we have to close the 2032d1f3e843089f381a035edc734156 tag at the end of the file.

Next, let’s take a look at well-organized html. Since it will be processed by the XML parsing engine, it must comply with all the rules of well-organized XML. Essentially, this means that all opening tags must have a corresponding closing tag. For example, the e388a4556c0f65e1904146cc1a846bee tag, which is not normally closed, must be closed with 94b3e26ee717c64999d7867364b1b4a3.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" 
version="1.0">
<xsl:template match="basketpage">
<html>
<head>
<title>shopping bag / adjust quantity</title> 
</head>
<body bgcolor="#cccc99" bgproperties="fixed" link="#990000" vlink="#990000">
<br>
?br> </xsl:template> 
</xsl:stylesheet>

In the body of the template, there are many xsl tags used to provide logic for data presentation. Two commonly used tags are explained below.

choose

The3e08d16b69ca6dceb52122b5e3e896ec tag is similar to the beginning of an if-then-else structure in traditional programming languages. In XSL, the choose tag indicates that in the part where the code enters, the assignment will trigger the action. The 1aab2a36c3da35537dba594d8b9f335a tag with assigned attributes follows the choose tag. If the assignment is correct, the content between the opening and closing tags of 1aab2a36c3da35537dba594d8b9f335a will be used. If the assignment is wrong, the content between the opening and closing tags of b490e3a477a758f8d417150b585fd42a is used. End the entire section with 0deb431ca822a5ae1672ac1bd025a592.


In this example, the when tag will check the xml for the quantity tag. If the quantity tag contains an error attribute with a value of true, the quantity tag will display the table cells listed below. If the value of the attribute is not true, xsl will display the content between the otherwise tags. In the example below, if the error attribute is not true, nothing will be displayed.

<xsl:choose>
<xsl:when test="quantity[@error=&#39;true&#39;]">
<td bgcolor="#ffffff"><img height="1" width="1" 
src="http://img.sparks.com/images/i-catalog/sparks_images/sparks_ui/clearpixel.gif"/></td>
<td valign="top" bgcolor="#ffffff" colspan="2">
<font face="verdana, arial" size="1" color="#cc3300"><b>*not enough in stock. your quantity was adjusted accordingly.</b>
</font></td> 
</xsl:when>
<xsl:otherwise> 
</xsl:otherwise>
</xsl:choose>

for-each

431e46b64b4819f2ac967516fbb4b43f tag can be used to apply the same style sheet to multiple situations of similar xml data. For us, a series of product information can be taken out from the database and formatted uniformly on the web page. Here is an example:

<xsl:for-each select="package">
<xsl:apply-templates select="product"/>
</xsl:for-each>

for-each 循环在程序遇到标签时开始。这个循环将在程序遇到标签时结束。一旦这个循环运行,每次标签出现时都会应用这个模板。

四、生成html

将来的某一时刻,浏览器将会集成xml解析引擎。到那时,你可以直接向浏览器发送xml和xsl文件,而浏览器则根据样式表中列出的规则显示xml数据。不过,在此之前开发者们将不得不在他们服务器端的系统里创建解析功能。

在sparks.com,我们已经在java servlet里集成了一个xml解析器。这个解析器使用一种称为xslt (xsl transformation)的机制,按xsl标签的说明向xsl模板中添加xml数据。

当我们的java servlet处理http请求时,servlet检索动态生成的xml,然后xml被传给解析引擎。根据xml文件中的指令,解析引擎查找适当的xsl样式表。解析器通过dom结构创建html文件,然后这个文件再传送给发出http请求的用户。

如果你选择使用sax模型,解析器会通读xml源程序,为每个xml标签创建一个事件。事件与xml数据对应,并最终按xsl标签向样式表中插入数据。

以上就是用XML和XSL来生成动态页面的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn