XML study (Lesson 5: XSL Style Sheets (Part II))

The order of conditions

Like in programming languages generally have the instructions on conditions such as IF, SELECT CASE, ELSE. Etc. to choose from, the XSL commands have conditions such as xsl: if , xsl: choose , xsl: khi , and xsl: Không thì . When expression of Element xsl: if , xsl: khi , or xsl: Không thì  has value true , then it is inside the template will be created (instantiated).

Usually, if the simplicity of the test we use the xsl: if . If it is a bit confusing because, depending on the circumstances we have to do different work, we use choose / When / If not,

Attribute values of the test of xsl: if and xsl: When is an expression to calculate. Thisexpression can be a comparison or a kind of XPath expression. The results of thiscalculation will be true if it returns one of the following values:



  • A node has at least one node
  • A number of other zero
  • A piece (fragment) Tree
  • A text string is not empty (non-empty)
To illustrate how to use XSL commands on the conditions we will use the source file name catalog.xml following:
<?xml version="1.0"?>
<catalog>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, an evil sorceress, and her own 
childhood to become queen of the world.</description>
   </book>
   <book id="bk107">
      <author>Thurman, Paula</author>
      <title>Splish Splash</title>
      <genre>Romance</genre>
      <price>4.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description>
   </book>
   <book id="bk108">
      <author>Knorr, Stefan</author>
      <title>Creepy Crawlies</title>
      <genre>Horror</genre>
      <price>4.95</price>
      <publish_date>2000-12-06</publish_date>
      <description>An anthology of horror stories about roaches, centipedes, scorpions and other 
insects.</description>
   </book>
   <book id="bk109">
      <author>Kress, Peter</author>
      <title>Paradox Lost</title>
      <genre>Science Fiction</genre>
      <price>6.95</price>
      <publish_date>2000-11-02</publish_date>
      <description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway 
discovers the problems of being quantum.</description>
   </book>
   <book id="bk110">
      <author>O'Brien, Tim</author>
      <title>Microsoft .NET: The Programming Bible</title>
      <genre>Computer</genre>
      <price>36.95</price>
      <publish_date>2000-12-09</publish_date>
      <description>Microsoft's .NET initiative is explored in detail in this deep programmer's 
reference.</description>
   </book>
</catalog>
Here is an example of using xsl: if :
<xsl:for-each select="//book">
   <tr>
      <td>
         <xsl:value-of select="title"/>
      </td>
      <td>
         <xsl:if test="price > 6">
            <xsl:attribute name="bgcolor">cyan</xsl:attribute>
         </xsl:if>
         <xsl:value-of select="price"/>
      </td>
   </tr>
</xsl:for-each>
In the above example, Attribute BGColor only be created with the value of cyan when the price of the book is greater than 6. Our purpose is to use blue light to that book as a base for cost ( price ) higher than 6.

Here is an example of using xsl: choose :
<xsl:for-each select="//book">
   <div>
      <xsl:choose>
         <xsl:when test="self::*[genre = 'Romance']">
            <xsl:attribute name="style">background-color: pink</xsl:attribute>
         </xsl:when>
         <xsl:when test="self::*[genre = 'Fantasy']">
            <xsl:attribute name="style">background-color: lightblue</xsl:attribute>
         </xsl:when>
         <xsl:otherwise>
            <xsl:attribute name="style">background-color: lightgreen</xsl:attribute>
         </xsl:otherwise>
      </xsl:choose>
      <xsl:value-of select="title"/>
   </div>
</xsl:for-each>
In the above example of the Cascading Style Sheet style attribute will have value forbackground-color vary depending on the type of book. If it is pink Romance, Fantasy, then lightblue, but if not, or Fantasy Romance (ie xsl: nếu không) lightgreen it. This colorwill be used as background for headings (title) of the book. Tags <xsl:choose> noticed a pair, </ xsl: choose> used to package the xsl: khi, and xsl: Không thì inside.

The following is a listing of catalog.xsl style sheet full, including both how to use xsl: if and xsl: you said:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:template match="/">
      <HTML>
         <HEAD>
            <TITLE>Book Lovers' Catalog</TITLE>
         </HEAD>
         <BODY>
            <Center>
               <H1>Book Lovers' Catalog</H1>
            </Center>
            <TABLE Border="1" Cellpadding="5">
               <TR>
                  <TD align="center" bgcolor="silver">
                     <b>ID</b>
                  </TD>
                  <TD align="center" bgcolor="silver">
                     <b>Author</b>
                  </TD>
                  <TD align="center" bgcolor="silver">
                     <b>Title</b>
                  </TD>
                  <TD align="center" bgcolor="silver">
                     <b>Genre</b>
                  </TD>
                  <TD align="center" bgcolor="silver">
                     <b>Price</b>
                  </TD>
                  <TD align="center" bgcolor="silver">
                     <b>Published Date</b>
                  </TD>
                  <TD align="center" bgcolor="silver">
                     <b>Description</b>
                  </TD>
               </TR>
               <xsl:for-each select="//book">
                  <TR>
                     <TD>
                        <xsl:value-of select="@id"/>
                     </TD>
                     <TD>
                        <xsl:value-of select="author"/>
                     </TD>
                     <TD>
                        <xsl:choose>
                           <xsl:when test="self::*[genre = 'Romance']">
                              <xsl:attribute name="style">background-color: pink</xsl:attribute>
                           </xsl:when>
                           <xsl:when test="self::*[genre = 'Fantasy']">
                              <xsl:attribute name="style">background-color: lightblue</xsl:attribute>
                           </xsl:when>
                           <xsl:otherwise>
                              <xsl:attribute name="style">background-color: lightgreen</xsl:attribute>
                           </xsl:otherwise>
                        </xsl:choose>
                        <xsl:value-of select="title"/>
                     </TD>
                     <TD>
                        <xsl:value-of select="genre"/>
                     </TD>
                     <TD>
                        <xsl:if test="price > 6">
                           <xsl:attribute name="bgcolor">cyan</xsl:attribute>
                        </xsl:if>
                        <xsl:value-of select="price"/>
                     </TD>
                     <TD>
                        <xsl:value-of select="publish_date"/>
                     </TD>
                     <TD>
                        <xsl:value-of select="description"/>
                     </TD>
                  </TR>
               </xsl:for-each>
            </TABLE>
         </BODY>
      </HTML>
   </xsl:template>
</xsl:stylesheet>
After adding the sentence:
<?xml-stylesheet type="text/xsl" href="catalog.xsl"?>
catalog.xml early records, double click the file name catalog.xml, Internet Explorer will display the following results:



Book Lovers' Catalog


ID Author Title Genre Price Published Date Description
bk102 Ralls, Kim Midnight Rain Fantasy 5.95 2000-12-16 A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.
bk107 Thurman, Paula Splish Splash Romance 4.95 2000-11-02 A deep sea diver finds true love twenty thousand leagues beneath the sea.
bk108 Knorr, Stefan Creepy Crawlies Horror 4.95 2000-12-06 An anthology of horror stories about roaches, centipedes, scorpions and other insects.
bk109 Kress, Peter Paradox Lost Science Fiction 6.95 2000-11-02 After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.
bk110 O'Brien, Tim Microsoft .NET: The Programming Bible Computer 36.95 2000-12-09 Microsoft's .NET initiative is explored in detail in this deep programmer's reference.



Dùng nhiều Templates trong một Style Sheet

In the previous article, XSL style sheet for each one that came up only a Template (included in the table), and it applies to the Root Element of the XML document.

Actually, XSL allows us to use more of a Style Sheet Templates. Maybe you should do it for two reasons. First, you can separate out each part of the presentation of XML documents, so easy to debug or modify any part of the Style sheet. Second, you can use XPath expressions to apply styles to any type of data depending on its value.

When a style sheet contains many templates, you specify the application of them in the presentation logic (presentation logic) by using the apply-templates . Typically, you create a template for Root Element is said to process an entire document and use the apply-templates for the preparation of the Element is located within the top-level template that. These Templates can be called when needed, and the top-level template will handle all data without any mention Template. That is, if the Element does not have the template to apply to it, then we use the general template of the Root Element.

For example the following style sheet include: a top-level template to apply to the Document (Root) Element, a template for the Product Element with Attribute value UnitPrice is greater than 70, a template for other Product Element, and a template for the Element Quantity:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:template match="/">
      <HTML>
         <HEAD>
            <TITLE>Northwind Home Page</TITLE>
         </HEAD>
         <BODY>
            <P>Customer Order</P>
            <P>Order No: 
               <xsl:value-of select="Order/@OrderNo"/>
            </P>
            <P>Date: 
               <xsl:value-of select="Order/OrderDate"/>
            </P>
            <P>Customer: 
               <xsl:value-of select="Order/Customer"/>
            </P>
            <TABLE Border="0">
               <TR>
                  <TD>ProductID</TD>
                  <TD>Product Name</TD>
                  <TD>Price</TD>
                  <TD>Quantity Ordered</TD>
               </TR>
               <xsl:for-each select="Order/Item">
                  <TR>
                     <xsl:apply-templates></xsl:apply-templates>
                  </TR>
               </xsl:for-each>
            </TABLE>
         </BODY>
      </HTML>
   </xsl:template>
   <xsl:template match="Product[@UnitPrice > 70]">
      <TD>
         <xsl:value-of select="@ProductID"/>
      </TD>
      <TD>
         <A>
            <xsl:attribute name="HREF">Products.asp?ProductID=
               <xsl:value-of select="@ProductID"/>
            </xsl:attribute>
            <xsl:value-of select="."/>
         </A>
      </TD>
      <TD>
         <FONT color="red">
            <xsl:value-of select="@UnitPrice"/>
         </FONT>
      </TD>
   </xsl:template>
   <xsl:template match="Product">
      <TD>
         <xsl:value-of select="@ProductID"/>
      </TD>
      <TD>
         <A>
            <xsl:attribute name="HREF">Products.asp?ProductID=
               <xsl:value-of select="@ProductID"/>
            </xsl:attribute>
            <xsl:value-of select="."/>
         </A>
      </TD>
      <TD>
         <xsl:value-of select="@UnitPrice"/>
      </TD>
   </xsl:template>
   <xsl:template match="Quantity">
      <TD>
         <xsl:value-of select="."/>
      </TD>
   </xsl:template>
</xsl:stylesheet>


When applying this style sheet to the XML document order, we will record the following HTML:

<HTML>
   <HEAD>
      <TITLE>Northwind Home Page</TITLE>
   </HEAD>
   <BODY>
      <P>Customer Order</P>
      <P>Order No: 1047</P>
      <P>Date: 2002-03-26</P>
      <P>Customer: John Costello</P>
      <TABLE Border="0">
         <TR>
            <TD>ProductID</TD>
            <TD>Product Name</TD>
            <TD>Price</TD>
            <TD>Quantity Ordered</TD>
         </TR>
         <TR>
            <TD>1</TD>
            <TD>
               <A HREF="Products.asp?ProductID=1">Chair</A>
            </TD>
            <TD>70</TD>
            <TD>6</TD>
         </TR>
         <TR>
            <TD>2</TD>
            <TD>
               <A HREF="Products.asp?ProductID=2">Desk</A>
            </TD>
            <TD><FONT color="red">250</FONT></TD>
            <TD>1</TD>
         </TR>
      </TABLE>
   </BODY>
</HTML>


Part BODY of the HTML on the display as follows:

Customer Order
Order No: 1047
Date: 2002-03-26
Customer: John Costello
ProductID Product Name Price Quantity Ordered
1 Chair 70 6
2 Desk 250 1


How to apply style sheet to XML

Before proceeding further study of other commands XSL style sheet, we need to understand and know how to apply a style sheet to an XML document.

Apply a Style Sheet is a function of an XML parser such as MSXML of Internet Explorer. You can store an XML parser to apply a style sheet into a XML or simply by inserting a processing instruction in the XML file, or write a few lines of code.

XML parser used to display

If we store the XSL style sheet file in a file name order Order.xsl then we can add the instruction processing xml-stylesheet in the XML file as following order:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="Order.xsl"?>
<Order OrderNo="1047">
   <OrderDate>2002-03-26</OrderDate>
   <Customer>John Costello</Customer>
   <Item>
      <Product ProductID="1" UnitPrice="70">Chair</Product>
      <Quantity>6</Quantity>
   </Item>
   <Item>
      <Product ProductID="2" UnitPrice="250">Desk</Product>
      <Quantity>1</Quantity>
   </Item>
</Order>
When an XML parser to read this XML file, the xml-stylesheet processing instructionparser application security profile Order.xsl style sheets to transform XML.

Attribute type that kind of style sheet is applied, or the XSL style sheet or a cascading style sheet (CSS) , a style sheet to specify the color and font. Here it is the XSL style sheet in the text.

Attribute href to know the name of the file used as a Style Sheet, the path of the file name that can be relatively or absolutely. Here is the filename of the style sheet Order.xsl , no path, meaning it should be in the same folder as Order.xml .

If we use a program like Internet Explorer browser 5.5 or 6.0 it will automatically load the style sheet to add posture for XML documents.

While Internet Explorer displays the results, if you use the Menu Command View | Source of the browser, you will only see the XML code, do not see HTML code as you guessed. Want to see the HTML code, as a result of the transform XML by applying XSL you need to download the tool called the Internet Explorer XML / XSL Viewer Tools from Microsoft Downloads .

After Unzip the downloaded file, you right click the name of two files msxmlval.inf and msxmlvw.inf then select install to install them as add-ins (these components into a functional program is available) on the Internet programs Explorer as shown in the picture below. 

Now want to see the HTML code, right click on your Web page in IE and then select the command View XSLOutput from PopUpMenu as in the image below:


Used to transform the XSL code

Using a programming language to make an XML parser processing an XML document will depend on circumstances. If you use Microsoft XML parser, a component called MSXML, in programming, the XML document will be loaded into a Document Object Model (XMLDom) object . Then you can call the method transformNode to apply an XSL style sheet is loaded in a previous XMLDom another object for processing XML.

As in the example below, we use two DOM, to load a file Order.xml , another one to load Order.xsl in VBScript running on Active Server Pages (ASP) :
Dim objXML  'for XML DOM 
Dim objXSL  'for DOM XSL 
Dim strResult  'Resultant document 
'Load the XML document. 
Set objXML = CreateObject ("Microsoft.XMLDom") objXML.Async = False 
objXML.Load "c: \ Order.xml" 
'Load the XSL style sheet. 
Set objXSL = CreateObject ("Microsoft.XMLDom") objXSL.Async = False 
objXSL.Load "c: \ Order.xsl" 
'apply the style sheet to XML
objXML.transformNode strResult = (objXSL)
After running the above code, strResult results will contain records.

The following figure illustrates the role of the XSLT processor in Working transform an XML file based on an XSLT (from now on we can use XSLT for the XSL as well) file:


We also have the JavaScript code to run in the browser, instead of WebServer, as shown in the Web page below. It also gives the same results as when using IE to display XML directly.
<HTML>
   <HEAD>
      <TITLE>sample</TITLE>
      <SCRIPT language="javascript">
         function init()
           {
             var srcDOM = new ActiveXObject("Msxml2.DOMDocument.4.0");
             srcDOM.async=false;
             srcDOM.load("order.xml");

             var xsltDOM= new ActiveXObject("Msxml2.DOMDOCUMENT.4.0");
             xsltDOM.async = false;
             xsltDOM.load("order.xsl");

             resDOM.innerHTML = srcDOM.transformNode(xsltDOM);
           }
      </SCRIPT>
   </HEAD>
   <BODY onload="init()">
      <div id="resDOM"></div>
   </BODY>
</HTML>
Perhaps you ask why we do not use XML directly as above to display Web pages. Note that we can use this technique to transform a XML with XSL and then displays it inside a DIV , which is a restricted area within the Web page, do not account for the Web. Here, when the Web started to load ( onload event), IE call function init () to transform XML and assign the result to the innerHTML property of the DIV resDOM .

There is a different method can also be used instead transformNode is transformNodeToObject . The main difference between these two methods are:
  • transformNode: The results of this method is a tree as a text string, typically an HTML file. It can be displayed in a browser or saved to a file.
  • transformNodeToObject: The results of this method is to go in a different object, then the object could then be processed further.
When we use either method above, in fact, the source object (source object) need not be a complete dossier. It may just be a node of XML documents. If it is just a node, then the XSLT processor to see him set Node, Nodes, and the descendants of it as a complete dossier. Similarly, an object XSL XSL file can be a full, or a node inside an XSL file.


(Continued)

1 comment:

  1. As a beginner this tutorial is very helpful. I bookmarked this for future reference. Really XML is not so difficult to learn. During I search easy lesson for XML I found one more link which is very well described. Sharing that link for your reference http://jharaphula.com/get-started-with-xml-for-beginners

    ReplyDelete