【问题标题】:How to use inline conditional (if then else) in XSLT?如何在 XSLT 中使用内联条件(if then else)?
【发布时间】:2015-05-29 15:45:11
【问题描述】:

是否可以在 XSLT 中执行内联条件(if then else)?比如:

<div id="{if blah then blah else that}"></div>

或者一个真实的用例/例子:

<div id="{if (@ID != '') then '@ID' else 'default'}"></div>

【问题讨论】:

  • 在 XSLT 2.0 中,是的。在 XSLT 1.0 中,没有 - 尽管 可能 有一种方法可以在 某些 情况下构造单线。贴一个实际的例子。

标签: xslt sharepoint sharepoint-2010 xslt-1.0 dataviewwebpart


【解决方案1】:

如 cmets 中所述,if () then else 构造仅在 XSLT/XPpath 2.0 中受支持。

我自己的偏好是使用冗长但可读的:

<xsl:template match="some-node">
    <div> 
        <xsl:attribute name="ID">
            <xsl:choose>
                <xsl:when test="string(@ID)">
                    <xsl:value-of select="@ID"/>
                </xsl:when>
                <xsl:otherwise>default</xsl:otherwise>
            </xsl:choose>
        </xsl:attribute>
    </div>
</xsl:template>

或者更短的:

<xsl:template match="some-node">
    <div ID="{@ID}"> 
        <xsl:if test="not(string(@ID))">
            <xsl:attribute name="ID">default</xsl:attribute>
        </xsl:if>
    </div>
</xsl:template>

但是,如果您喜欢神秘代码,您可能会喜欢:

<xsl:template match="some-node">
    <div ID="{substring(concat('default', @ID), 1 + 7 * boolean(string(@ID)))}"> 
    </div>
</xsl:template>

或:

<xsl:template match="some-node">
    <div ID="{concat(@ID, substring('default', 1, 7 * not(string(@ID))))}"> 
    </div>
</xsl:template>

【讨论】:

  • 单线很酷,如果附上评论,很容易消化
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2016-04-19
  • 2023-03-22
  • 2021-11-30
  • 2019-04-25
相关资源
最近更新 更多