在 xsl:param xsl:if 测试条件中引用属性值



我正在尝试从xsl:param中检索属性值,并在xsl:if测试条件中使用它。所以给定以下 xml

<product>
  <title>The Maze / Jane Evans</title> 
</product>

和 XSL

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>
<xsl:param name="test" select="Jane"/>
 <xsl:template match="title[contains(., (REFERENCE THE SELECT ATTRIBUTE IN PARAM))]">
   <h2>
    <xsl:value-of select="substring-before(., '/')"/>
   </h2>
   <p>
    <xsl:value-of select="substring-after(., '/')"/>
   </p>
 </xsl:template>
 <xsl:template match="title">
   <h2><xsl:value-of select="."/></h2>
 </xsl:template>
</xsl:stylesheet>

我想回来

The Maze
Jane Evans

您在以下行中有问题

<xsl:param name="test" select="Jane"/>

这定义了一个名为 testxsl:param,其值是名为 Jane 的当前节点 ('/') 的子元素。由于 top 元素是<product>而不是<Jane>test 参数具有空节点集的值(和一个字符串值 - 空字符串)。

你想要(注意周围的撇号):

<xsl:param name="test" select="'Jane'"/>

整个处理任务可以相当容易地实现

此 XSLT 1.0 转换

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <xsl:param name="pTest" select="'Jane'"/>
 <xsl:template match="title">
  <xsl:choose>
    <xsl:when test="contains(., $pTest)">
       <h2>
        <xsl:value-of select="substring-before(., '/')"/>
       </h2>
       <p>
        <xsl:value-of select="substring-after(., '/')"/>
       </p>
    </xsl:when>
    <xsl:otherwise>
      <h2><xsl:value-of select="."/></h2>
    </xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

应用于提供的 XML 文档时

<product>
    <title>The Maze / Jane Evans</title>
</product>

产生所需的正确结果

<h2>The Maze </h2>
<p> Jane Evans</p>

解释

XSLT 1.0 语法禁止在匹配模式中引用变量/参数。这就是为什么我们有一个与任何title匹配的模板,并在模板中指定以特定的、想要的方式进行处理的条件。

XSLT 2.0 解决方案

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <xsl:param name="pTest" select="'Jane'"/>
 <xsl:template match="title[contains(., $pTest)]">
   <h2>
     <xsl:value-of select="substring-before(., '/')"/>
   </h2>
   <p>
     <xsl:value-of select="substring-after(., '/')"/>
   </p>
 </xsl:template>
 <xsl:template match="title">
   <h2><xsl:value-of select="."/></h2>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档(如上)时,将再次生成相同的所需正确结果

<h2>The Maze </h2>
<p> Jane Evans</p>

解释

XSLT

2.0 没有 XSLT 1.0 的限制,变量/参数引用可以在匹配模式中使用。

术语$test是指测试参数的值。使用$test

例如:

 <xsl:template match="title[contains(., $test)]">
   <h2>
    <xsl:value-of select="substring-before(., '/')"/>
   </h2>
   <p>
    <xsl:value-of select="substring-after(., '/')"/>
   </p>
 </xsl:template>

最新更新