XSLT:测试节点是否存在,无论它是当前节点的子节点还是孙节点

Spe*_*ump 1 xslt xpath xslt-1.0

我正在进行一些xslt转换,我刚刚发现在我当前的父节点和它的clildren之间可能有也可能没有额外的节点,具体取决于外部因素.所以现在我必须更改我的xslt代码以处理这两种情况:

方案1:

<parent>
   <child/>
   <child/>
<parent>
Run Code Online (Sandbox Code Playgroud)

方案2:

<parent>
   <nuisance>
      <child/>
      <child/>
   </nuisance>
<parent>
Run Code Online (Sandbox Code Playgroud)

我有以下情况:test="parent/child"或者使用这种格式访问父/节点.

我需要类似的东西 test="parent/magic(* or none)/child"

他们只知道可以解决这个问题的方法就是使用:

<xsl:choose>
    <xsl:when test="parent/child">
       <!-- select="parent/child"-->            
    </xsl:when>

    <xsl:otherwise>
       <!-- select="parent/*/child"-->      
    </xsl:otherwise>
</xsl:choose>
Run Code Online (Sandbox Code Playgroud)

但这将使我的代码大小增加三倍,并且将需要大量的手工劳动......

非常感谢!

Way*_*ett 5

为什么不简单地选择两者的结合?

<xsl:apply-templates select="parent/child|parent/*/child"/>
Run Code Online (Sandbox Code Playgroud)

这将在两种情况下选择正确的节点.

  • 虽然你经常可以阅读"|" 作为"或",它实际应该被读作"联合" - 它选择两个节点集的并集.XPath 2.0添加运算符"intersect"和"except"来查找两个节点集的交集或差异(它们被写为单词).在XSLT 2.0中,您还可以在路径的一个步骤中使用这些运算符:因此您可以编写`parent /(.|*)/ child`作为问题的解决方案. (2认同)