首页 文章

使用<xsl:choose>根据元素的祖先元素格式化元素

提问于
浏览
0

我是新手,我正在尝试在<xsl:when>元素中使用test来查看当前节点是否是早期节点的后代 . 然后,我想将适当的html标记应用于内容 . 我是xpath表达式的新手 .

具体来说,我想将<th>标签应用于作为<thead>元素后代的<tcell>元素 . 我想将<td>标签应用于作为<tbody>元素后代的<tcell>元素 . 我最好的猜测是我必须在<xsl:template match =“tcell”>元素中使用<xsl:choose>元素 . 我在测试中尝试了一些不同的xpath表达式,但它们都没有工作 .

Question: <xsl:choose>是最好的选择吗?

这是我的xml文档,适用的部分 . 文档结构无法更改 .

<table>
  <tgroup>
    <thead>
      <trow>
        <tcell>Column Head Text</tcell>
        <tcell>Column Head Text</tcell>
      </trow>
    </thead>
    <tbody>
      <trow>
        <tcell>Cell Text</tcell>
        <tcell>Cell Text</tcell>
      </trow>        
    </tbody>
  </tgroup>
 </table>

我想使用XSL / XPath生成一个包含 Headers 行和正文行的表 . 我的XSL样式表看起来像这样:

<xsl:template match="/">
  <html>
    <body>
    <xsl:apply templates />
    </body>
  </html>
</xsl:template>

<xsl:template match="table">
    <table>
        <xsl:apply-templates />
    </table>
</xsl:template>

<xsl:template match="tgroup">
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="thead">
    <thead>
        <xsl:apply-templates />
    </thead>
</xsl:template>

<xsl:template match="tbody">
    <tbody>
        <xsl:apply-templates />
    </tbody>
</xsl:template>       

<xsl:template match="trow">
    <tr>
        <xsl:apply-templates />
    </tr>
</xsl:template>

<!-- MY TROUBLE STARTS HERE -->
<xsl:template match="tcell">
    <xsl:choose>
      <xsl:when test="current()!=descendant::tbody">
        <th>
          <xsl:value-of select="."/>
        </th>
      </xsl:when>
      <xsl:otherwise>
        <td>
          <xsl:value-of select="."/>
        </td>
      </xsl:otherwise>
    </xsl:choose>
</xsl:template>

任何帮助,将不胜感激 .

Sample html output

<table>
  <tgroup>
    <thead>
     <tr>
      <th>Column Head Text</th>
      <th>Column Head Text</th>
     <tr>
    </thead>
    <tbody>
      <tr>
       <td>Cell Text</td>
       <td>Cell Text</td>
      </tr>
    </tbody>
  </tgroup>
 </table>

谢谢,M_66

1 回答

  • 0
    <xsl:template match="thead//tcell">
        <th>
            <xsl:value-of select="."/>
        </th>
    </xsl:template>
    
    <xsl:template match="tbody//tcell">
        <td>
            <xsl:value-of select="."/>
        </td>
    </xsl:template>
    

    或者如果您仍想使用 xsl:choose

    <xsl:template match="tcell">
        <xsl:choose>
            <xsl:when test="ancestor::thead">
                <th>
                    <xsl:value-of select="."/>
                </th>
            </xsl:when>
            <xsl:otherwise>
                <td>
                    <xsl:value-of select="."/>
                </td>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    

相关问题