Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a URL variable into xsl

Is it possible to pass a URL variable into xsl.

EG. http:www.somedomain.com/index.aspx?myVar=test&myVar2=anotherTest

I'd like to be able to use the values of myVar and myVar2 in the logic of my xsl file. Thanks.

like image 242
Strontium_99 Avatar asked Feb 09 '12 13:02

Strontium_99


2 Answers

Sure, you can. Use xsl:param element in xsl:stylesheet element and pass parameter from your XSL engine.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="url"/>

Then use string-functions, e.g.:

<xsl:variable name="right-part" select="substring-after($url, 'myVar=')"/>
<xsl:value-of select="substring-before(substring-before($right-part, 'myVar2='), '&amp;')"/>
<xsl:text>|</xsl:text>
<xsl:value-of select="substring-after($right-part, 'myVar2=')"/>
like image 83
Kirill Polishchuk Avatar answered Oct 20 '22 01:10

Kirill Polishchuk


Here is a more generic transformation that obtains any number of query string parameters from a given URL:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pUrl" select=
 "'http:www.somedomain.com/index.aspx?myVar=test&amp;myVar2=anotherTest&amp;myVar3=yetAnotherTest'"/>

 <xsl:template match="/">
     <xsl:call-template name="GetQueryStringParams"/>
 </xsl:template>

 <xsl:template name="GetQueryStringParams">
  <xsl:param name="pUrl" select="$pUrl"/>

      <xsl:variable name="vQueryPart" select=
      "substring-before(substring-after(concat($pUrl,'?'),
                                        '?'),
                      '?')"/>

      <xsl:variable name="vHeadVar" select=
       "substring-before(concat($vQueryPart,'&amp;'), '&amp;')"/>

       <xsl:element name="{substring-before($vHeadVar, '=')}">
         <xsl:value-of select="substring-after($vHeadVar, '=')"/>
       </xsl:element>

    <xsl:variable name="vRest" select="substring-after($vQueryPart, '&amp;')"/>

    <xsl:if test="string-length($vRest) > 0">
       <xsl:call-template name="GetQueryStringParams">
         <xsl:with-param name="pUrl" select=
         "concat('?', substring(substring-after($vQueryPart, $vHeadVar), 2))"/>
       </xsl:call-template>
    </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the wanted, correct result is produced:

<myVar>test</myVar>
<myVar2>anotherTest</myVar2>
<myVar3>yetAnotherTest</myVar3>
like image 41
Dimitre Novatchev Avatar answered Oct 19 '22 23:10

Dimitre Novatchev