【问题标题】:XSLT test to check whether <tr> parent node (<table>) has particular IDXSLT 测试检查 <tr> 父节点 (<table>) 是否具有特定 ID
【发布时间】:2011-12-21 10:02:18
【问题描述】:

我一直在努力解决这个问题的正确语法,它归结为:

如何测试父节点的属性是否有一定的值?

我正在转换一些 XHTML。我模板匹配&lt;tr&gt;,以便重新格式化该行中某些单元格的colspan 属性。为了进一步确信这只会发生在某些表中,我需要检查 &lt;table&gt; 所属的 &lt;tr&gt; 是否具有特定的 id 属性值。

<xsl:template match="tr">
<tr>
  <xsl:choose>
    <xsl:when test="(count(td[@colspan='2'])=2 and count(td)=3)">
        <td colspan="1">
          <xsl:copy-of select="td[1]/node()" />
        </td>
        <td colspan="4">
          <xsl:copy-of select="td[2]/node()" />
        </td>
    </xsl:when>
      <xsl:otherwise>
        <xsl:copy-of select="@*|node()" />
      </xsl:otherwise>
  </xsl:choose>
</tr>
</xsl:template>

这是我到目前为止的代码。我需要在我的 when 测试或另一个 xsl:ifxsl:when 中添加更多“和”来检查表属性。对于这种情况,让表 id="Transformable"。

为了澄清,我只希望在&lt;tr&gt; 所属的表的 id 为“Transformable”时进行上述转换。

任何帮助将不胜感激。

【问题讨论】:

  • 请问可以发布一些您的源 XML 吗?一个样本就完美了。

标签: css xml xslt xpath xhtml


【解决方案1】:

我猜你可以在模板匹配定义中使用parent 轴。

<xsl:template match="tr[parent::table/@id = 'Transformable']">
  This template matches only 'tr' within a 'table' with 'id' attribute which equals 'Transformable'.
</xsl:template>

更新:对于复杂的嵌套(如果 table 不是 tr 的直接父级) - 您可以使用 ancestor 轴。

<xsl:template match="tr[ancestor::table/@id = 'Transformable']">
  This template matches only 'tr' within a 'table' with 'id' attribute which equals 'Transformable'.
</xsl:template>

【讨论】:

  • +1 但要小心 - 它还取决于 tr 是否嵌套在 thead/tbody 等中。
  • 你是对的。在长嵌套的情况下,我会使用 'ancestor::' 而不是 'parent::'。
  • 希望没有嵌套表,其中一个嵌套在另一个 id='Transformable' 的表中,否则您也会匹配。这就是为什么最好看到 Xml 结构 ;-)
  • 可能最安全的是测试最里面的祖先表:ancestor::table[1]/@id = 'xyz'
  • 太棒了。谢谢大家的cmets。为了安全起见,我将使用 table[1]。
【解决方案2】:

您应该尝试类似(在您的测试子句中):
父::table[@id = 'Transformable']

【讨论】:

    【解决方案3】:

    您也可以使用代表父级的 .. 选择器

    <xsl:when test="..[@colspan='2']">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2017-05-04
      • 2016-08-29
      • 2011-06-09
      • 1970-01-01
      相关资源
      最近更新 更多