Tuesday, 7 December 2010

XSLT transforming and sorting XML

How can XSLT be used (a) to transform an XML structure and (b) to sort the contents of an XML document?

# To start the process, the XSLT processor begins with a node list containing only the document root. It finds the template matching this root node—typically the rule with match="/"—and instantiates the contents of the template in the result tree. If the template contains elements from the XSLT namespace that select other nodes to process, the sequence of matching and template content instantiation continues recursively until there are no nodes left to process. When processing is completed, the result tree represents the target document produced by the transformation.
It has some templates rules which have a pattern of identifying the nodes it matches and a template to be instantiate and output when the pattern is matched. During the process of transforming an XML document using an XSLT style sheet, XSLT walks the XML document tree, looking at each node in turn.
The processor compares each node on the XML document with the guide of each template rule in the style sheet and if the processor finds a node that matches a template rule's pattern, it outputs the rule's template.  A diagram for transformation process is as follows:


Previously, in blog there are number of enormous benefits for XSLT has been stated to transform XML documents. Such as one can carefully organize document content before formatting it for display with CSS or XSL-FO.
            XSLT also helps in sorting and the simplest way to do so in to use the <xsl:sort> element. This element allows sorting the nodes in a node set according to specified criteria. One of the most common operations performed on databases is sorting, in which items are organized according such as date, quantity, etc. For example, in the given code it uses the name element as the key and then sorts nodes within the node set in ascending order. The data type is set to text to indicate that the sorting routine is text-based.
<xsl:for-each select="studentdetails">
  <xsl:sort select="name" order="ascending"/>
  <div style="width:450px; padding:5px; margin-bottom:10px; border:5px double black;
    color:black; background-color:white; text-align:left">
    <xsl:apply-templates select="name"/>
    <xsl:apply-templates select="course"/>
    <xsl:apply-templates select="year"/>
    <hr />
    <xsl:apply-templates select="grade"/>
    <hr />
    <xsl:apply-templates select="email"/>
  </div>
</xsl:for-each>
In this example, the xsl:sort element is used to sort the student details prior to display each of them.

No comments:

Post a Comment