XSLT检查节点可用性

时间:2015-12-17 15:47:30

标签: xslt xslt-1.0

我在我的项目中使用XSLT 1.0。在我的XSLT转换中,我必须检查特定元素,如果存在 - 我必须执行一些连接或其他一些连接操作。

但是,我没有在这里找到一个选项,就像一些内置函数一样。

要求就像

<Root>
  <a></a>
  <b></b>
  <c></c>
</Root>

这是元素<a>,来自请求有效负载,然后我们需要执行<b><c>其他<c><b>的连接。

4 个答案:

答案 0 :(得分:3)

你可以通过模板匹配来实现:

<xsl:template match="Root[not(a)]">
  <xsl:value-of select="concat(c, b)"/>
</xsl:template>

<xsl:template match="Root[a]">
  <xsl:value-of select="concat(b, c)"/>
</xsl:template>

答案 1 :(得分:1)

沿着这些方向尝试:

<xsl:template match="/Root">
    <xsl:choose>
        <xsl:when test="a">
            <!-- do something -->
        </xsl:when>
        <xsl:otherwise>
            <!-- do something else -->
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

解释:测试返回由表达式a选择的节点集的布尔值。如果节点集非空,则结果为true。

答案 2 :(得分:1)

使用xsl:choose

测试元素是否存在
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"   
    version="1.0">

    <xsl:template match="/Root"> 
        <xsl:choose>
            <xsl:when test="a">
                <xsl:value-of select="concat(c, b)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="concat(b, c)"/>
            </xsl:otherwise>
        </xsl:choose>  
    </xsl:template>

</xsl:stylesheet>

或者在模板匹配的谓词中:

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

    <xsl:template match="/Root[a]"> 
         <xsl:value-of select="concat(c, b)"/> 
    </xsl:template>

    <xsl:template match="/Root[not(a)]"> 
         <xsl:value-of select="concat(b, c)"/>
    </xsl:template>

</xsl:stylesheet>

答案 3 :(得分:0)

在您的情况下,使用choose并在相应的xpath上使用a测试是否存在boolean()

<xsl:template match="Root">
  <xsl:choose>
    <xsl:when test="boolean(./a)">
      <xsl:value-of select="concat(./b, ./c)" />
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="concat(./c, ./b)" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>