Showing posts with label task7. Show all posts
Showing posts with label task7. Show all posts

Tuesday, 29 November 2011

XLink


XLink is the XML way of tackling the issue of creating links between documents. It is very similar to it’s HTML counterpart, the <a> tag. But having a dedicated element for handling linking is not in XML’s spirit ( it would impose unnecessary restrictions that would hamper flexibility ), therefore this functionality is implemented in a separate namespace ( xmlns:xlink=http://www.w3.org/1999/xlink ), and attributed to elements with by setting certain properties.

It can be used for the roles fulfilled by <a> in HTML – to enable the user to navigate to a different document; but they’re more versatile, and have a number of attributes that control it’s behaviour.

An XLink can be of two types: simple and extended. The simple XLink has similar similar capabilities to traditional HTML links: they provide a uni-directional connection between two resources.

Example of simple XLink usage:
 1 <?xml version="1.0"?>
 2 <links xmlns:xlink="http://www.w3.org/1999/xlink">
 3
 4     <blog xlink:type="simple"
 5         xlink:href="http://mihairotaru.blogspot.com">Ram's blog</blog>
 6
 7     <blog xlink:type="simple"
 8         xlink:href="http://native-dev.blogspot.com">Second blog</blog>
 9
10 </links>


Monday, 28 November 2011

Transforming XML documents with XSLT

The XSLT transformation pipeline involves four elements: the source XML document(s) with the XSLT stylesheets, an XSLT processor ( template processing engine ), and the resulting document(s).

The output format of an XSLT transformation ( actually, in the context of XSLT a transformation doesn’t actually transform the source XML document – but instead uses it as input for creating other documents ) can range from PDF files to plain text files; this is due to XSLT’s powerful templating mechanism and versatile XSL Formatting Objects.

Here’s an XSL template which will create an XML file based on movies.xml, and add a column which will represent the ‘value’ of the movie – it’s rating divided by it’s price:
 1 <?xml version="1.0" encoding="ISO-8859-1"?>
 2 <xsl:stylesheet version="1.0"
 4
 5 <xsl:output method="xml" version="1.0" indent="yes"/>
 6     <xsl:template match="/">
 7         <movies>
 8         <xsl:for-each select="movies/movie">
 9             <movie>
10             <xsl:copy-of select="./*"/>
11             <value><xsl:value-of select="rating div price"/></value>
12             </movie>
13         </xsl:for-each>
14         </movies>
15     </xsl:template>
16 </xsl:stylesheet>

Notes
-         this solution is not ideal, since some elements are hard-coded ( ‘movies’ and ‘movie’ ); these should be somehow deduced
-         xsl:for-each is used on L08 to select each ‘movie’ node in turn ( in the order they appear in the original XML file – ‘document order’ )
-         xsl:copy-of is used on L10 to create a copies of all the child nodes of the current node. This statement will copy the ‘title’, ‘year’, etc elements for each ‘movie’ element.
-         on L11, the value element is created. xsl:value-of is used to insert the value resulting from dividing the value of the ‘rating’ element with the value of the ‘price’ element of the current node.

Microsoft’s msxsl tool (http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21714 ) can be used to transform the original XML file into a new one, with the added <value> element:
 msxsl movies.xml transform.xsl -o new_movies.xml

Sorting is accomplished by using the xsl:sort element ( http://www.w3.org/TR/xslt#sorting ). xsl:sort can only appear as a child of an xsl:apply-templates or an xsl:for-each element. To sort the list of movies by the name of the title, we can simply add a line after L08 in the previous XSLT stylesheet:
9         <xsl:sort select="title">

The resulting XML document will have it’ elements sorted corresponding to the alphabetical order of their ‘title’ elements. So, ‘Apocalypto’ will appear the first, and ‘Year One’ as the last one.

Sunday, 27 November 2011

Styling XML documents with XSL

This blog post will describe the process of employing XSLT stylesheets for styling an XML document. It is very similar to using CSS – the stylesheet must be created, and the XML document should be told about the stylesheet. But that’s where the similarities stop; the two methods are very different in their approach.

Central to XSLT-based styling is the concept of a `template` - it is XSLT’s equivalent for CSS rules. XSLT will try to match the template’s pattern with the XML document; when it finds a match, it will perform the transformations described in the template body.

Here’s an XSL which would display the movies.xml file as a table:


<?xml version="1.0"?>
<xsl:stylesheet 
version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">
<html>
    <body style="font:12px Georgia;">
        <table style="border: 1px outset; background-color: lightgray;">
            <!--Generate table headings-->
            <tr bgcolor="#9acd32">
                <th>Title</th>
                <th>Year</th>
                <th>Rating</th>
            </tr>

            <!--Generate table rows-->
            <xsl:for-each select="movies/movie">
                <tr>
                    <td><xsl:value-of select="title"/></td>
                    <td><xsl:value-of select="year"/></td>
                    <td><xsl:value-of select="rating"/></td>
                </tr>
            </xsl:for-each>
        </table>
    </body>
</html>
</xsl:template>
</xsl:stylesheet>

The XML file needs to know about this XSL stylesheet; so this line needs to be added to the XML file, assuming the XSL has the ‘movies-xsl-style.xsl’:
2 <?xml-stylesheet type="text/xsl" href="movies-xsl-style.xsl"?>

This is how the XML file was rendered by Firefox 8.0:

Which is exactly how I wanted it to look. This example illustrates the advantages and potential drawbacks of using XSL fro styling XML documents.

Among the drawbacks, the most obvious one is the learning curve – although XSL stylesheets are XML documents themselves, they have numerous tags with a specific role ( more precisely, those inside the http://www.w3.org/1999/XSL/Transform namespace ), which means that it is still a technology that one would need to spend considerable amounts of time to learn. It can be considered a fully-fledged programming language, with loops, if’s and variables.

Browser support is also quite limited for XSLT 2.0; however, this doesn’t diminish it’s usefulness on the server side. Instead of serving the XML + XSL documents and relying on the client’s browser to perform the transformations, the transformations could be run on the server ( using tools such as Saxon or AltovaXML ), generating XHTML files which would then be served to the clients.

One of the most important advantages of using XSL to style XML documents is the fact that it respects the principle of keeping the data and presentation separate, while providing the same styling capabilities as with CSS stylesheets, and much more powerful constructs.

Saturday, 26 November 2011

Styling XML documents with CSS


XML can be styled using CSS in a similar way to (X)HTML; in fact, the same CSS file could be used by both XML and XHTML files. In this post, I will demonstrate, using the XML file ( Pastebin link ) created in the previous post, how to add CSS styling to an XML document. This blog post is based on the short tutorial in section 2.2 of the CSS2.1 W3C Recommendation ( http://www.w3.org/TR/CSS2/intro.html#xml-tutorial ).

Before telling the XML file about the CSS, obviously the CSS file needs to be created. I wanted the table to have a gray background, a serif font, and green background for the table headers. I ended up creating this short CSS file:
 1 body
 2 {
 3     font: 12px Georgia;
 4 }
 5
 6 table
 7 {
 8     border-width: 1px;
 9     border-style: outset;
10     background-color: lightgray;
11 }
12
13 th
14 {
15     background-color: #9acd32;
16 }

Then, I simply added a line to the XML file:
2 <?xml-stylesheet type="text/css" href="style.css"?>

Not a very smart approach, as I soon realized. Instead of rendering a lovely table, the browser simply printed all the information about the movies, in a single row. Which makes perfect sense; the CSS states that table headers should have a green background. But how is the browser supposed to know which part of the XML file should be the headers ? Or where is the table ? All it sees is a well-formed XML file.

After massaging the CSS file further – while not touching the XML, in keeping with the ‘separate data from style’ principle – I managed to get to something resembling a table:
 1 movies
 2 {
 3     font: 12px Georgia;
 4     margin: 3px;
 5     width: 260px;
 6     border-width: 1px;
 7     border-style: outset;
 8     background-color: lightgray;
 9 }
10
11 title  { background-color: lightcyan; }
12
13 movie  { display: block; background-color: honeydew }
14
15 title  { display: inline-block; width: 100px; border-right: 2px solid gray; }
16 rating { display: inline-block; width: 50px;  border-right: 1px solid gray; }
17 price  { display: inline-block; width: 50px;  border-right: 1px solid gray; }
18 year   { display: inline-block; width: 40px; }

How the XML was rendered by Firefox 8.0:








Looks like a table, sure, but my dreams of green table header backgrounds were shattered; it cannot be accomplished without modifying the XML file. And I really don’t want to do that – because then I would be using the XML file as (X)HTML. Obviously, XHTML is XML by definition; but it’s not wrong – in fact, it is required – for XHTML to have tags like ‘body’, ‘table’, ‘td’, ‘tr’, etc.

XML, on the other hand, I intend to use it for it’s intended purpose – storing data in a future-proof way. What if I later decide to write another parser that would use my XML files with data about movies ? Had I decided to change the XML to accommodate CSS styling, my parser would have to look for and parse elements such as ‘body’, ‘h1’, etc – and I would much rather have to deal with ‘movie’ elements, which have the ‘title’, ‘year’, etc elements. In other words, the semantics of the XML document would be preserved, without being contaminated with presentational tags – or simply tags that don’t make sense in the context of the data which is stored.

I think this highlights very well the problems with styling XML with CSS – while it can work, the desired effects might be difficult to achieve without contaminating the XML document with additional data. This is not desirable; the presentational document should accommodate the data, not the other way around. While attempting this, the CSS file might end up bloated, and using unintuitive work-arounds.

However, styling XML documents with CSS might work very well for simpler document types, which do not require the control that my example did. For example, if the document only contains a few textual elements, then basic presentational properties can be set easily – font, colors, etc.

But probably the most enticing feature of CSS over the alternative ( XSL ) is the fact that it leverages knowledge of a widespread, almost ubiquitous technology, since CSS has been used extensively for decades. It has a very large user base, and these programmers would be able to style XML documents using CSS with little learning required. XSL, on the other hand, can be quite daunting to learn.

Ultimately, I think a decision should be taken on a per-case basis. In simple cases, CSS works just fine; but when XML documents have a more complex structure, the power of XSL should probably be invoked instead.

How to generate XHTML from XML using XSL

The Extensible Stylesheet Language Family (XSL) can be used to transform XML documents into other types of XML documents ( such as XHTML ), or into completely different formats – such as PDF, or simple plain text.

One of the most common applications of XSL is to present documents stored inside XML files as XHTML, for consumption by browsers. The principle behind XSL is simple: take a well-formed XML document, find the needed elements/nodes/text ( using XPath ), and place them in a template. Assuming a valid XSL template and a well-formed XML file were used, the resulting document will also be a valid XHTML document.

Taking the document used in the previous blog post, which contains information about a few movies, I will assume the goal is to generate the XHTML code which will present the information inside the file.

To accomplish this, an XSL Style Sheet must be created. The name is slightly misleading, because XSL can be used not only to configure and customize how an XML document is presented, but transformations can be applied as well. This will not, of course, alter the XML document, but might not represent all the data inside it – some information can be filtered out, new information might be added by the XSL template.

I have come up with the following XSL file:
 1 <?xml version="1.0"?>
 2 <xsl:stylesheet
 3     version="1.0"
 4     xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
 5     <xsl:template match="/">
 6         <!--XHTML generation begins here-->
 7         <html>
 8             <body>
 9                 <h2>A list of movies</h2>
10                 <p>This list comprises several movies</p>
11                 <table>
12 
13
                    <!--Generate table headings-->
14                     <tr>
15                         <th>Title</th>
16                         <th>Year</th>
17                         <th>Rating</th>
18                     </tr>
19 
20
                    <!--Generate table rows-->
21                     <xsl:for-each select="movies/movie">
22                         <tr>
23                             <td><xsl:value-of     select="title"/></td>
24                             <td><xsl:value-of select="year"/></td>
25                             <td><xsl:value-of select="rating"/></td>
26                         </tr>
27                     </xsl:for-each>
28                 </table>
29             </body>
30         </html>
31         <!--XHTML generation finishes here-->
32     </xsl:template>
33 </xsl:stylesheet>


A few things to note:
- I intentionally omitted the price information, to underline how XSL might create the wrong impression of the information contained in the XML file. This information is available inside the XML, but the XSLT omits it.
1. XPath is used on L05, to define the elements to which the template should be applied. In this case, the ‘/’ means that it should be applied to the whole document. Again, very similar to paths in Unix – ‘/’ represents the root of the filesystem.
2. XPath is used again on L21; the statements contained by the for-each element will be executed for each node matching the XPath expression “movies/movie”.
3. Another important XSL element, the xsl:value-of is used on lines 23-25; it relies on the concept of the “current element”. In the context of a for-each, this means that each element matching for-each’s XPath ( in this case, "movies/movie" ) will become the “current element”, in sequence. We have five movie elements in our XML file, so each of these will become, in turn, the current element. xsl:value-of will extract the value of certain child elements - title, year and rating, and place these values instead of itself.

One more step is needed – we need to tell the XML file that we made an XSL stylesheet for it – otherwise, when opened in a browser, it will simply be displayed as before. To do this, a line needs to be added to the XML file:
2 <?xml-stylesheet type="text/xsl" href="movies-style.xsl"?>

When opened in an XSL-compliant browser ( all modern browsers are compatible with XSL ), the XML file will be processed using our XSL file ( movies-style.xsl ), and the result of this process is XHTML – which will then be displayed by the browser.