HTML and CSS   XSLT   JavaScript   Images   Soft   Etc  
Andrey Shitov

XSLT string resources 2 December 2005


Task: Remind what function document() can do.

Function document() is usually used to locate external files. However, few programmers remember (and some never knew) that it also allows to parse the current XSLT template—the calling file itself.

Just write document('').

Compatibility

Both popular XSLT processors—libxslt and msxsl—enable this equally well.

Take for example the XSLT template that returns the name of the month (a string) when the input is the following XML code:

<?xml version="1.0" encoding="UTF-8"?>
<date year="2005" month="12" day="2"/>

The resource strings are stored directly in the XSLT file. To retrieve them, use simple XPath expression document('')/xsl:stylesheet/... following usual XSLT rules.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
	version="1.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:als="http://www.artlebedev.ru/xsl">
	<xsl:template match="/">	
		<xsl:value-of select="date/@day"/>
		<xsl:text> </xsl:text>
		<xsl:value-of
			select="document('')/xsl:stylesheet/als:strings/months/item
			[position() = current()/date/@month]/text()"/>
		<xsl:text> </xsl:text>
		<xsl:value-of select="date/@year"/>
	</xsl:template>
	<als:strings>
		<months>
			<item>January</item>
			<item>February</item>
			<item>March</item>
			<item>April</item>
			<item>May</item>
			<item>June</item>
			<item>July</item>
			<item>August</item>
			<item>September</item>
			<item>October</item>
			<item>November</item>
			<item>December</item>
		</months>
	</als:strings>
</xsl:stylesheet>

Note that you have to declare a namespace.


Order a design...