首页 > 解决方案 > XML/XSL if else 子字符串

问题描述

如果条目太长,我想用 if 子句对XML/XSL中的变量进行子串化。

我尝试过这样的事情,但它不是那样工作的。

                    <xsl:variable id="newId" select="./newId"/>
                    <xsl:template match="newId">
                        <xsl:choose>
                            <xsl:when test="string-length() &lt; 15">
                                <xsl:value-of select="newId"/>  
                            </xsl:when>
                            <xsl:otherwise>
                                 <xsl:value-of select="substring(.,1,15)" />
                                 <br>
                                 <xsl:value-of select="substring(.,16)" />
                                 </br>
                            </xsl:otherwise>
                        </xsl:choose>

标签: xmlif-statementvariablesxsltsubstring

解决方案


您的代码中有几处需要更改。

  • xsl:variable 有一个 'name' 属性,而不是 'id'
  • 字符串长度函数需要一个参数

这是我的做法:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
       <xsl:variable name="newId" select="'SomeText123456789'"/>
        <xsl:choose>
            <xsl:when test="string-length($newId) &lt; 15">
                <xsl:value-of select="$newId"/>  
            </xsl:when>
            <xsl:otherwise>
                 <xsl:value-of select="substring($newId,1,15)" />
                 <br>
                 <xsl:value-of select="substring($newId,16)" />
                 </br>
            </xsl:otherwise>
        </xsl:choose>
  </xsl:template>
  
</xsl:stylesheet>

看到它在这里工作:https ://xsltfiddle.liberty-development.net/jxDjind


推荐阅读