How do I access value of current item when using for-each in XSL?

46 views Asked by At

Using the code below, how do I access the current item in the loop without specifying $array[1]?

    <xsl:variable name="array" as="element()*">
        <item>https://www.example.com/_resources/data/blogs.xml</item> <!--item 1-->
        <item>https://www.example.com/_resources/data/blogs2.xml</item> <!--item 2-->
    </xsl:variable>
    
    <xsl:for-each select="$array/item">
        <xsl:apply-templates select="document($array[1])/hero-image/img" /><!--How do we access value of current item without specifying $array[1]) -->
    </xsl:for-each>
1

There are 1 answers

2
Michael Kay On

Firstly, the variable $array holds a sequence of item elements, and you want to iterate over these elements, not over their children. You have written $array/item, which is short for $array/child::item, which selects the children of the elements in the array, not the elements themselves.

Secondly, you refer to the current item as .. So you would want:

<xsl:for-each select="$array">
    <xsl:apply-templates select="document(.)/hero-image/img"/>
</xsl:for-each>

But that can be abbreviated to

<xsl:apply-templates select="$array/document(.)/hero-image/img"/>

Note: you are using XSLT 2.0+ here, and it's best to mention that in the question (or simply add the relevant tag, which I shall do for you).