Arty
Arty

Reputation: 859

Pass a variable in an Xpath String

I have an xsl file which contains some xPath..

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

<xsl:output method="xml" indent="yes" omit-xml-declaration="yes" encoding="UTF-8"/>

<xsl:variable name="ref_num" select="ABCD"/>    

<xsl:template match="holiday">
    <fromPrice>
        <xsl:copy-of select="document('/file/to/path/in/documents/FILE1.xml',/)/dataroot/Tour/RefNo[.='ABHC']/preceding-sibling::AXL "/>
    </fromPrice>
</xsl:template>

</xsl:stylesheet>

The Scenario..
The xml file is returning the <fromPrice> values from the FILE1.xml(of which the value is coming from the <AXL> element) file correctly as follows:

FILE1.xml

<Tour>
    <Allocation>0</Allocation>
    <Available>16</Available>
    <AXL>4658</AXL>
    <ALO>2195</ALO>
    <RefNo>AABC</RefNo>
</Tour>
<Tour>
    <Allocation>0</Allocation>
    <Available>16</Available>
    <AXL>1295</AXL>
    <ALO>595</ALO>
    <RefNo>ATSS</RefNo>
</Tour>

The problem:
I wanted $ref_num to be passed in the xPath at the "/RefNo[.='ABHC']" so that RefNo contains the value ABCD for the variable $ref_num. That way, if $ref_num changes, I don't have to hard code the xPath at "/RefNo[.='ABHC']" again.

So far I tried the following:
* /RefNo[.=' "+$ref_num+ "'] and that didn't work.{Stylesheet error. Can't Compile}
* /RefNo[.=' \"+$ref_num+ \"'] and that didn't work too.{Stylesheet error. Can't Compile}
* /RefNo[.='+$ref_num+'] and that didn't work too.{Stylesheet error. Can't Compile}

Upvotes: 0

Views: 465

Answers (1)

Tomalak
Tomalak

Reputation: 338108

I don't see where that would be a problem, just use the variable in the expression.

<xsl:variable name="ref_num" select="AABC" />
<xsl:variable name="filePath" select="'/file/to/path/in/documents/FILE1.xml'" />
<xsl:variable name="tours" select="document($filePath)/dataroot" />

<xsl:template match="holiday">
    <fromPrice>
        <xsl:copy-of select="$tours/Tour[RefNo = $ref_num]/AXL" />
    </fromPrice>
</xsl:template>

Hint: XPath expressions are not strings. This is not interpolation.

Upvotes: 2

Related Questions