Home  >  Article  >  Backend Development  >  Detailed explanation of code for generating dynamic pages using XML and XSL

Detailed explanation of code for generating dynamic pages using XML and XSL

黄舟
黄舟Original
2017-03-28 17:00:072022browse

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

At sparks.com, we use xml to standardize different systems from javaobjects to html data display. Data representation between.

In particular, we found that it is easier to share and manipulate data as long as it is standardized in a very basic xml structure. There are many effective ways to use xml. Here is a detailed introduction to 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 the database is not new, but generating xml is. Here we introduce the specific generation steps

Using xsl as a template language

xsl (Extensible Stylesheet Language) is a good way to define the xml data display format. It will be more efficient if it is written as several

statictemplates to generate html#. ##xml plus xsl equals html. This may not sound right, but our html page that users see is actually the result of the combination of xml and xsl. The power of xml comes from its flexibility. But unfortunately, it is sometimes too flexible, so that you will be faced with 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 decisions:

What data to involve

Whether to use dtd (file type definition)

Whether you want to use DOM (Document Object Model) or SAX (Simplified API for XML) to parse

Determine the data:

Because there is no standard XML format, developers are free to develop their own format. However, if your format is only recognized by one application, then you can only run the program to use that format. It would obviously be more helpful if there are other programs that also understand your xml format. When an XML format is modified, the system using it may also need to be modified, so you should create the format as complete as possible. Because most systems ignore tags they do not recognize, the safest way to change an XML format is Add tags instead of modifying them

Click here to see an example of the xml data format

At sparks.com, we look at all the product data needed for different product displays. All pages use all data, but we have also developed a very complete xml data format that applies to 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 instead of 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 based on

events

, 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 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 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 XSL, see Using kind.

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.

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

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 template consists of carefully organized xsl and

html tags

.

Start building the templateThe 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. This article comes from http://bianceng.cn (ProgrammingIntroduction)

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

3e08d16b69ca6dceb52122b5e3e896ecThe tag is similar to the beginning of the

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.

    在这个例子里,when标签会为quantity标签检查xml。如果quantity标签里含有值为真的error属性,quantity标签将会显示列在下面的表格单元。如果属性的值不为真,xsl将会显示otherwise标签间的内容。在下面的实例里,如果error属性不真,则什么都不会被显示。

<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标签可以用来对相似xml数据的多种情况应用同一个样式表。对于我们来说,可以从数据库中取出一系列产品信息,并在web页上进行统一格式化。这里有一个例子:

<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标签向样式表中插入数据

The above is the detailed content of Detailed explanation of code for generating dynamic pages using XML and XSL. For more information, please follow other related articles on the PHP Chinese website!

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