繁体   English   中英

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

[英]Referencing attribute value in xsl:param xsl:if test condition

我试图从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的当前节点('/')的子元素。 由于顶部元素是<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM