Pages

Thursday, January 26, 2012

Use the position() function to locate and output content with XSLT

The position() function allows you to specify which one of a given element you want to select for transformation. For example, the table below identifies two drugs which interact with each other. However, you decide you would rather have this information in list format instead of tabular, but there are too many tables in your XML data set to convert them by hand. So you want to write an XSL transformation to reformat this content on output.

<table>
<tgroup>
<thead>Drug Interaction Table 1</thead>
<tbody>
<row><entry><drugname>Warfarin</drugname></entry>
<entry><drugname>Aspirin</drugname></entry></row>
</tbody>
</table>

All of the drug interactions tables consist of two columns (two entries in each row), with the object drug listed first, the precipitant drug listed second. You can match on the entry tags with the position () function like so:

<xsl:template match="row/entry[position() = 1]/drugname">
<br/>
<xsl:text>Object: </xsl:text>
<xsl:apply-templates/>
</xsl:template>

<xsl:template match="row/entry[position() = 2]/drugname">
<br/>
<xsl:text>Precipitant: </xsl:text>
<xsl:apply-templates/>
</xsl:template>

The resulting output would look like this (assuming other templates for the rest of the data):

Object: Warfarin
Precipitant: Aspirin

You can also abbreviate your position() function like so:

<xsl:template match="row/entry[1]/drugname">

The number in the square brackets indicates the position without having to write out position() =.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.