XSLT for each collection cycle

Is it possible to create a loop for each loop in XSLT, not for a node set, but for my own collection of elements? For example, I split a line and the result was a set of lines. And I need to create a node for each item in the collection. I know that the problem can be solved with a recursive pattern, but I want to know if recursion can be avoided.

+3
source share
3 answers

There are two obvious, simple solutions, one of which is only supported in XSLT 2.0:

I. General decision

This works with both XSLT 1.0 and XSLT 2.0.

node -set , ( <xsl:stylesheet>.)

:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my" exclude-result-prefixes="my"
 >
 <xsl:output method="text"/>

 <my:nodes>
   <string>Hello </string>
   <string>World</string>
 </my:nodes>

 <xsl:variable name="vLookup"
    select="document('')/*/my:nodes/*"/>

 <xsl:param name="pSearchWord" select="'World'"/>

 <xsl:template match="/">
   <xsl:if test="$pSearchWord = $vLookup">
     <xsl:value-of select=
       "concat('Found the word ', $pSearchWord)"/>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>

XML- ( ), :

Found the word World

, xxx:node-set().

II. XSLT 2.0/XPath 2.0

XSLT 2.0/XPath 2.0 . , , :

 <xsl:variable name="vLookup" as="xs:string*"
    select="'Hello', 'World'"/>

:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 >
 <xsl:output method="text"/>

 <xsl:variable name="vLookup" as="xs:string*"
    select="'Hello', 'World'"/>

 <xsl:param name="pSearchWord" select="'World'"/>

 <xsl:template match="/">
   <xsl:if test="$pSearchWord = $vLookup">
     <xsl:value-of select=
       "concat('Found the word ', $pSearchWord)"/>
   </xsl:if>
 </xsl:template>
</xsl:stylesheet>
+1

XPath node-set(). , . msxsl exslt .

MSDN msxsl:node-set() xsl:for-each:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                xmlns:user="http://www.contoso.com"
                version="1.0">
    <xsl:variable name="books">
        <book author="Michael Howard">Writing Secure Code</book>
        <book author="Michael Kay">XSLT Reference</book>
    </xsl:variable>

    <xsl:template match="/">
        <authors>
            <xsl:for-each select="msxsl:node-set($books)/book"> 
                <author><xsl:value-of select="@author"/)</author>
            </xsl:for-each>
        </authors>
    </xsl:template>
</xsl:stylesheet>
+1

What platform are you using, which XSLT processor are you using? You will need to provide your string collection as a data type supported by your XSLT processor. Which one exactly depends on the API supported by your XSLT processor. For example, with .NET XslCompiledTransform, you would need to provide an XPathNodeIteratator.

0
source

Source: https://habr.com/ru/post/1744303/


All Articles