字符串中每个字母的XSLT

vel*_*koz 9 xslt foreach xpath

我正在编写一个XSLT转换(对于XSL-FO),并且需要为字符串值中的每个字母重复一些内容,例如:

如果字符串存储在MyData/MyValue字符串中(例如MyData.MyValue ="something"),我需要像这样的for-each:

<xsl:for-each select="MyData/MyValue"> <!-- What goes here to iterate through letters? -->
  <someTags>
    <xsl:value-of select="Letter" /> <!-- What goes here to output current letter? -->
  </someTags>
</xsl:for-each>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Tre*_*key 12

您可以使用调用模板并传递参数,然后使用递归来调用模板,直到没有字符为止.

示例在下面添加.

在这个xml上

<?xml version="1.0" encoding="utf-8"?>
<data>
        <node>something</node>
</data>
Run Code Online (Sandbox Code Playgroud)

而这个xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="data/node">
            <xsl:call-template name="for-each-character">                    
                    <xsl:with-param name="data" select="."/>
            </xsl:call-template>
    </xsl:template>

        <xsl:template name="for-each-character">                
                <xsl:param name="data"/>
                <xsl:if test="string-length($data) &gt; 0">
                        <someTags>                            
                                <xsl:value-of select="substring($data,1,1)"/>
                        </someTags>
                        <xsl:call-template name="for-each-character">
                                <xsl:with-param name="data" select="substring($data,2)"/>
                        </xsl:call-template>
                </xsl:if>
        </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

然后,您将能够在if语句中操作以执行更多操作!


Luk*_*der 7

你可以尝试这种经常被证明可以一次又一次工作的丑陋黑客:

<xsl:for-each select="//*[position() &lt;= string-length(MyData/MyValue)]">
  <someTags>
    <xsl:value-of select="substring(MyData/MyValue, position(), 1)"/>
  </someTags>
</xsl:for-each>
Run Code Online (Sandbox Code Playgroud)

如果//*匹配的字符串多于字符串中的字符数,这将会起作用...当然,这对于那些读完你的代码的穷人来说也应该得到奇怪的评论...... ;-)

注意:我知道那里有XSLT纯粹主义者.但是当你需要完成工作而不关心XSLT的超级冗长时,那么有时候这些技巧真棒!IMO

还要注意:我在这里提出了一个性能问题,看看迭代或递归是否表现更好:XSLT迭代或递归性能

  • @BC:有充分理由反对.这不是一个很好的解决方案,它是一个黑客.它大部分时间都可以工作,但不能保证快速或可靠.我猜这个问题很好.但总的来说,请在此处阅读:http://stackoverflow.com/questions/6681191/xslt-iteration-or-recursion-performance and here:http://stackoverflow.com/questions/506348/how-do-i-知道 - 我 - XSL-是高效的,和美丽.我希望XSLT真正支持循环,但是哦...... (2认同)