Home Backend Development XML/RSS Tutorial Detailed explanation of code for generating dynamic pages using XML and XSL

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

Mar 28, 2017 pm 05:00 PM

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());
Copy after login

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();
}
Copy after login

This code generates the xml file header. The 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 ( in this example). At the end of the file, only the tag needs to be closed.

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

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 and 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();
}
Copy after login

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 determines the mode of the xsl template. The match attribute is required and here points to the xml tag . In our system, the tag contains the tag, which allows the xsl template to access the product information embedded in the tag. Once again we have to close the 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

tag, which is not normally closed, must be closed with

.
<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>
Copy after login
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

The 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 tag with assigned attributes follows the choose tag. If the assignment is correct, the content between the opening and closing tags of will be used. If the assignment is wrong, the content between the opening and closing tags of is used. End the entire section with .

在这个例子里,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>
Copy after login

for-each

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

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

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Filtering and sorting XML data using Python Filtering and sorting XML data using Python Aug 07, 2023 pm 04:17 PM

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Using Python to merge and deduplicate XML data Using Python to merge and deduplicate XML data Aug 07, 2023 am 11:33 AM

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Python implements conversion between XML and JSON Python implements conversion between XML and JSON Aug 07, 2023 pm 07:10 PM

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling errors and exceptions in XML using Python Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Import XML data into database using PHP Import XML data into database using PHP Aug 07, 2023 am 09:58 AM

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Use PHP and XML to process and display geolocation and map data Use PHP and XML to process and display geolocation and map data Aug 01, 2023 am 08:37 AM

Processing and displaying geolocation and map data using PHP and XML Overview: Processing and displaying geolocation and map data is a common requirement when developing web applications. PHP is a popular server-side programming language that can interact with data in XML format. This article explains how to use PHP and XML to process and display geolocation and map data, and provides some sample code. 1. Preparation: Before starting, you need to ensure that PHP and related extensions, such as Simple, are installed on the server

See all articles