我有一个巨大的xsl文件,但我使用“tokenize”来解析逗号分隔字符串的部分抛出一个错误。为简单起见,我将其分解为仅测试令牌化部分,似乎无法取得任何进展。我一直收到以下错误:
表达预期。记号化( - > [< - 文本], '')
我尝试在其他帖子中使用一些示例xsl共享,但从未设法让它工作。我很难理解为什么我的xsl代码无效。这看起来很简单,但我想我错过了一些简单的东西。任何有助于我朝着正确方向前进的帮助都将非常感激。
XSL:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
<xsl:for-each select="tokenize([text],',')"/>
<items>
<item>
<xsl:value-of select="."/>
</item>
</items>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
XML:
<?xml-stylesheet type="text/xsl" href="simple.xsl"?>
<root>
<text>Item1, Item2, Item3</text>
</root>
我期待XML输出如下:
<items>
<item>Item1</item>
<item>Item2</item>
<item>Item3</item>
</items>
谢谢!
如DevNull所述,tokenize()是一个XSLT 2.0函数。但是,如果您的处理器支持EXSLT,请使用 str:tokenize()函数。否则,您将需要用户递归来分割逗号分隔值,如此...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*" />
<xsl:template match="/">
<items>
<xsl:apply-templates select="root/text"/>
</items>
</xsl:template>
<xsl:template match="text">
<xsl:call-template name="tokenize">
<xsl:with-param name="csv" select="." />
</xsl:call-template>
</xsl:template>
<xsl:template name="tokenize">
<xsl:param name="csv" />
<xsl:variable name="first-item" select="normalize-space(
substring-before( concat( $csv, ','), ','))" />
<xsl:if test="$first-item">
<item>
<xsl:value-of select="$first-item" />
</item>
<xsl:call-template name="tokenize">
<xsl:with-param name="csv" select="substring-after($csv,',')" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
我看到4件事错了:
你正在使用 tokenize()
在1.0样式表中。您需要将版本更改为2.0并使用2.0处理器。如果您使用Web浏览器进行转换,则基于 xml-stylesheet
处理指令,你可能没有使用2.0处理器。
你的标记化的第一个参数([text]
) 是无效的。只是用 text
。
你过早地关闭了你的 xsl:for-each
。
你正在输出一个 <items>
对于每个项目。放在 <items>
在外面 xsl:for-each
。
变更示例:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
<items>
<xsl:for-each select="tokenize(text,',')">
<item>
<xsl:value-of select="."/>
</item>
</xsl:for-each>
</items>
</xsl:template>
</xsl:stylesheet>
要使用2.0处理器真正获得所需的输出,我还建议使用 xsl:output
和 normalize-space()
:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="/root">
<items>
<xsl:for-each select="tokenize(text,',')">
<item>
<xsl:value-of select="normalize-space(.)"/>
</item>
</xsl:for-each>
</items>
</xsl:template>
</xsl:stylesheet>