How to use a function from one xsl to another

I have two xsl files: "one.xsl" and "two.xsl"

one.xsl:

<xsl:function name="x:trans" as="xs:string"> <xsl:param name="str"></xsl:param> <xsl:variable name="res1" select="x:translate_string($str)"/> <xsl:sequence select="$res1"/> </xsl:function> </xsl:stylesheet> 

I want to use the "x: trans" function in "one.xsl"

How to reference a function to another file?


The problem is that when I try to call this function as follows:

 < xsl:value-of select="x:trans('Hello World')"/> 

I get the following error message from the browser:

Link to undeclared namespace prefix: 'x'

+6
xslt
source share
3 answers

Besides the correct answers you need for <xsl:include> or <xsl:import> (I would recommend the latter, as the former can often lead to duplication errors), another problem is the following

  • The function name must belong to the namespace .

  • The namespace must be declared (defined and prefixed) in the same file in which the function is defined.

  • Any function call must prefix the function name and the prefix must be bound to the same namespace to which the function name belongs

Here is a simple example:

I. The deleteA.xsl file defines the function my:double

 <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:my="my:my" > <xsl:function name="my:double" as="xs:double"> <xsl:param name="pArg" as="xs:double"/> <xsl:sequence select="2*$pArg"/> </xsl:function> </xsl:stylesheet> 

II. The deleteB.xsl file imports the deleteB.xsl file and uses the my:double function:

 <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:my="my:my"> <xsl:import href="deleteA.xsl"/> <xsl:output method="text"/> <xsl:template match="/"> <xsl:sequence select="my:double(.)"/> </xsl:template> </xsl:stylesheet> 

III. The conversion contained in deleteB.xsl applies to the following XML document :

 <t>1</t> 

and the correct result is obtained :

 2 

Additional comment . The browser does not currently support XSLT 2.0 conversions. xsl:function is only available in XSLT 2.0+.

+7
source share

You want to either make <xsl:include /> or <xsl:import /> . <xsl:include /> simpler (it just drags everything), while <xsl:import /> more flexible (if there are patterns that collide between them, a higher call speed of the call-by-call is better defined and generally reasonable).

Change additional information:

You need to make sure that you invoke templates in the imported stylesheet using the appopriate namespace. The easiest way is to make sure you have xmlns: foo mappings in the stylesheets, although you can call foo: template in one stylesheet as bar: template in another if xmlns: bar was instead.

+4
source share

In the two.xsl file:

 <xsl:include href="one.xsl" /> 

See also the inclusion of the XSLT 2.0 specification .

+1
source share

All Articles