Các lệnh về điều kiện
Giống như trong ngôn ngữ lập trình thông thường ta có các instructions về điều kiện như IF, SELECT CASE, ELSE .v.v.. để lựa chọn, trong XSL ta có các lệnh về điều kiện như xsl:if, xsl:choose, xsl:when, vàxsl:otherwise. Khi expression của Element xsl:if, xsl:when, hay xsl:otherwise có trị số true, thì cái Template nằm bên trong nó sẽ được tạo ra (instantiated).Thường thường, nếu công việc thử tính đơn giản ta dùng xsl:if. Nếu nó hơi rắc rối vì tùy theo trường hợp ta phải làm những công tác khác nhau thì ta dùng choose/when/otherwise.
Trị số của Attribute test của xsl:if và xsl:when là một expression để tính. Expression nầy có thể là một so sánh hay một expression loại XPath. Kết quả việc tính nầy sẽ là true nếu nó trả về một trong các trị số sau đây:
- Một bộ node có ít nhất một node
- Một con số khác zero
- Một mảnh (fragment) Tree
- Một text string không phải là trống rỗng (non-empty)
Dưới đây là một thí dụ dùng xsl:if:
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>
Trong thí dụ trên, Attribute bgcolor chỉ được tạo ra với trị số cyan khi price của book lớn hơn 6. Mục đích của ta là dùng màu xanh da trời nhạt để làm nền cho sách nào có giá (price) cao hơn 6.
<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>
Dưới đây là một thí dụ dùng xsl:choose:
Trong thí dụ trên Attribute style của Cascading Style Sheet sẽ có những trị số cho background-color khác nhau tùy theo loại sách. Nếu là Romance thì pink, Fantasy thì lightblue, còn nếu không phải là Romance hay Fantasy (tức là xsl:otherwise) thì lightgreen. Màu nầy sẽ được dùng làm nền cho đề mục (title) của sách. Để ý là cặp Tags
<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>
Sau đây là listing của một catalog.xsl style sheet đầy đủ, trong đó có cả hai cách dùng xsl:if và xsl:when nói trên:
Sau khi thêm câu:
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>
vào đầu hồ sơ catalog.xml, double click lên tên file catalog.xml, Internet Explorer sẽ hiển thị kết quả sau:
xml-stylesheet type="text/xsl" href="catalog.xsl"?>
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. |
Bạn có thể tải về catalog.xml và catalog.xsl tại đây.
Dùng nhiều Templates trong một Style Sheet
Trong bài trước, trong mỗi XSL Style Sheet ta thấy vỏn vẹn chỉ có một Template (bảng kẻm in), và nó được áp dụng vào Root Element của tài liệu XML.Thật ra, XSL cũng cho phép ta dùng nhiều Templates trong một Style Sheet. Có thể bạn cần làm việc ấy vì hai lý do. Thứ nhất, bạn có thể phân chia cách trình bày ra từng phần của tài liệu XML, để dễ debug hay sửa đổi bộ phận nào của Style sheet. Thứ hai, bạn có thể dùng XPath expressions để áp dụng kiểu trình bày nào vào loại dữ liệu nào tùy theo trị số của nó.
Khi một Style Sheet chứa nhiều templates, bạn chỉ định việc áp dụng của chúng vào luận lý trình bày (presentation logic) bằng cách dùng lệnh apply-templates. Thông thường, bạn tạo một Template cho Root Element nói là để chế biến cả tài liệu và dùng lệnh apply-templates để chế biến những Element nằm bên trong cái top-level template ấy. Những Templates nầy có thể được gọi lúc nào cần, và cái top-level template sẽ xử lý mọi dữ liệu không có Template nào nhắc tới. Tức là nếu Element nào không có template để áp dụng cho nó thì ta dùng cái template tổng quát của Root Element.
Thí dụ như cái Style Sheet sau đây gồm có: một top-level template để áp dụng vào Document (Root) Element, một template cho những Element Product với Attribute UnitPrice có trị số lớn hơn 70, một template cho những Element Product khác, và một template cho những 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>
|
Khi áp dụng Style Sheet nầy vào cái tài liệu đặt hàng XML, ta sẽ có hồ sơ HTML sau đây:
<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> |
Phần BODY của HTML trên hiển thị như sau:
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 |
Cách áp dụng Style Sheet vào tài liệu XML
Trước khi tiếp tục học thêm các lệnh khác của XSL Style Sheet, ta cần hiểu và biết cách áp dụng một Style Sheet vào một tài liệu XML.Áp dụng một Style Sheet là một chức năng của một XML parser như MSXML của Internet Explorer. Bạn có thể bảo một XML parser áp dụng một Style Sheet vào một XML bằng cách hoặc là chỉ cần nhét một processing instruction vào đầu hồ sơ XML, hoặc là viết một vài dòng code.
Dùng XML parser để hiển thị
Nếu ta lưu trữ XSL Style Sheet của hồ sơ đặt hàng trong một file tên Order.xsl thì ta có thể thêm một hàngprocessing instruction xml-stylesheet vào đầu hồ sơ đặt hàng XML như sau:Khi một XML parser đọc hồ sơ XML nầy, cái processing instruction xml-stylesheet bảo parser áp dụng hồ sơ style sheet Order.xsl để transform XML.
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>
Attribute type cho biết loại style sheet được áp dụng, hoặc là XSL style sheet hoặc là cascading style sheet (CSS), một loại style sheet dùng để chỉ định màu và kiểu chữ. Ở đây nó là XSL style sheet trong dạng text.
Attribute href cho biết tên của file dùng làm Style Sheet, path của tên file ấy có thể là tương đối hay tuyệt đối. Ở đây filename của style sheet là Order.xsl, không có path, nên có nghĩa là nó nằm trong cùng một folder vớiOrder.xml.
Nếu ta dùng một chương trình trình duyệt như Internet Explorer 5.5 hay 6.0 nó sẽ tự động load Style Sheet để thêm dáng điệu cho tài liệu XML.
Trong lúc Internet Explorer hiển thị kết quả, nếu bạn dùng Menu Command View | Source của browser, bạn sẽ chỉ thấy code của XML, chớ không thấy code HTML như bạn đoán. Muốn xem được code HTML, là kết quả của việc transform XML bằng cách áp dụng XSL bạn cần tải về chương trình công cụ gọi là Internet Explorer XML/XSL Viewer Tools từ Microsoft Downloads.
Sau khi Unzip file vừa tải về, bạn right click tên của hai files msxmlval.inf và msxmlvw.inf rồi chọn installđể cài chúng làm Add-ins (những thành phần thêm chức năng vào một chương trình có sẵn) vào chương trình Internet Explorer như trong hình dưới đây.
Bây giờ muốn xem code HTML, bạn right click lên trang Web trong IE rồi chọn command View XSLOutput từ PopUpMenu như trong hình dưới đây:
Hình ảnh này đã bị thay đổi kích thước nhằm tránh làm vỡ giao diện. Bấm vào đây để xem ảnh ở kích thước đầy đủ ( 789x252 )
Hình ảnh này đã bị thay đổi kích thước nhằm tránh làm vỡ giao diện. Bấm vào đây để xem ảnh ở kích thước đầy đủ ( 824x514 )
Dùng code để transform với XSL
Cách dùng một ngôn ngữ lập trình để bảo một XML parser chế biến một tài liệu XML sẽ tùy thuộc vào hoàn cảnh. Nếu bạn dùng Microsoft XML parser, một component tên MSXML, trong lập trình thì tài liệu XML sẽ được loaded vào trong một Document Object Model (XMLDom) object. Kế đó bạn có thể gọi methodtransformNode để áp dụng một XSL style sheet đã được loaded trước đó vào một XMLDom object khác để chế biến XML.Như trong thí dụ dưới đây, ta dúng hai DOM, một cái để load file Order.xml, một cái khác để load Order.xsltrong VBScript chạy trên Active Server Pages (ASP):
Sau khi chạy đoạn code trên, strResult sẽ chứa hồ sơ kết quả.
Dim objXML ' DOM for XML Dim objXSL ' DOM for 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 strResult = objXML.transformNode(objXSL)
Hình dưới đây minh họa vai trò của XSLT processor trong công tác transform một hồ sơ XML dựa vào một XSLT (từ giờ trở đi ta có thể dùng từ XSLT thế cho XSL cũng được) file:
Ta cũng có thể code bằng JavaScript để chạy trong Browser, thay vì trong WebServer, như cho thấy trong trang Web dưới đây. Nó cũng cho ra cùng một kết quả như khi dùng IE để hiển thị XML trực tiếp.
Hình ảnh này đã bị thay đổi kích thước nhằm tránh làm vỡ giao diện. Bấm vào đây để xem ảnh ở kích thước đầy đủ ( 708x453 )
Có lẽ bạn hỏi tại sao ta không dùng thẳng XML như phía trên để hiển thị trang Web. Lưu ý là ta có thể dùng kỹ thuật nầy để Transform một XML với XSL rồi hiển thị nó bên trong một DIV, tức là một vùng giới hạn bên trong trang Web, chớ không chiếm cả trang Web. Tại đây khi trang Web bắt đầu load (onload event), IE gọifunction init() để transform XML rồi assign kết quả vào property innerHTML của DIV resDOM.
<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>
Có một method khác ta cũng có thể dùng thay cho transformNode là transformNodeToObject. Sự khác biệt chính giữa hai methods nầy là:
- transformNode: Kết quả của method nầy là một tree dưới dạng text string, điển hình là một hồ sơ H
Không có nhận xét nào :
Đăng nhận xét