use*_*697 12 xml xslt xslt-1.0
我有一个巨大的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>
Run Code Online (Sandbox Code Playgroud)
XML:
<?xml-stylesheet type="text/xsl" href="simple.xsl"?>
<root>
<text>Item1, Item2, Item3</text>
</root>
Run Code Online (Sandbox Code Playgroud)
我期待XML输出如下:
<items>
<item>Item1</item>
<item>Item2</item>
<item>Item3</item>
</items>
Run Code Online (Sandbox Code Playgroud)
谢谢!
Dan*_*ley 10
我看到4个错误:
您正在使用tokenize()1.0样式表.您需要将版本更改为2.0并使用2.0处理器.如果您使用Web浏览器进行转换,则根据xml-stylesheet处理指令,您可能没有使用2.0处理器.
tokenize([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>
Run Code Online (Sandbox Code Playgroud)
要使用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>
Run Code Online (Sandbox Code Playgroud)
正如 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>
Run Code Online (Sandbox Code Playgroud)