Xslt 使用条件将XSL变量设置为节点集
这个问题很类似于。主要区别在于,如果XPath没有找到与筛选器匹配的节点,我希望返回第一个未筛选的结果 我这里的代码是有效的,但我觉得这是一种黑客行为,不是很好的XSL风格。在这种情况下,每个章节节点由一个字符串id标识。变量Xslt 使用条件将XSL变量设置为节点集,xslt,Xslt,这个问题很类似于。主要区别在于,如果XPath没有找到与筛选器匹配的节点,我希望返回第一个未筛选的结果 我这里的代码是有效的,但我觉得这是一种黑客行为,不是很好的XSL风格。在这种情况下,每个章节节点由一个字符串id标识。变量showChapter是标识章节的字符串。如果没有找到具有此id属性的章节,我想返回第一章 相关代码: <xsl:param name="showChapter" /> <!-- if $showChapter does not match any ch
showChapter
是标识章节的字符串。如果没有找到具有此id属性的章节,我想返回第一章
相关代码:
<xsl:param name="showChapter" />
<!-- if $showChapter does not match any chapter id attribute,
set validShowChapter to id of first chapter.
-->
<xsl:variable name="validShowChapter">
<xsl:choose>
<xsl:when test="/book/chapter[@id=string($showChapter)][position()=1]">
<xsl:value-of select="$showChapter" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="/book/chapter[position()=1]/@id" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<!-- I want $chapter to be a valid node-set so I can use it in
XPath select statements in my templates
-->
<xsl:variable
name="chapter"
select="/book/chapter[@id=string($validShowChapter)][position()=1]"
>
这种方法是否像我认为的那样糟糕,如果是的话,你能告诉我一个更好的解决方案吗?我使用的是PHP5的XSLT处理器处理的XSLT1.0,但欢迎使用XSLT2.0解决方案 以下方法应该有效。在您的示例中,大量使用
position()
和string()
是不必要的,顺便说一句:
<xsl:param name="showChapter" />
<xsl:variable name="foundChapter" select="/book/chapter[@id = $showChapter]" />
<!-- Will select either the first chapter in $foundChapter, or
the first chapter available if $foundChapter is empty -->
<xsl:variable name="chapter"
select="($foundChapter | /book/chapter[not($foundChapter)])[1]" />
以下各项应能起作用。在您的示例中,大量使用
position()
和string()
是不必要的,顺便说一句:
<xsl:param name="showChapter" />
<xsl:variable name="foundChapter" select="/book/chapter[@id = $showChapter]" />
<!-- Will select either the first chapter in $foundChapter, or
the first chapter available if $foundChapter is empty -->
<xsl:variable name="chapter"
select="($foundChapter | /book/chapter[not($foundChapter)])[1]" />
非常感谢!我知道我写的东西太可怕了,不是最优雅的解决方案。非常感谢!我知道我写的东西太可怕了,不是最优雅的解决方案。