如何编写递归XSLT代码

时间:2016-06-23 09:29:53

标签: xml xslt recursion tree

我有动态XML数据,我使用以下xslt代码生成html。 XML结构包含章节,子章节,核对表和汇总节点。

  • <chapter>包含<subchapter><checklist>
  • <subchapter> contanins <subchapter><checklist>
  • <checklist>包含<summary>

我的代码可以运行但是,在检查清单之前一直添加子章节的内容。如果章节涉及清单,子章节点(第一个清单),则首先创建子章节内容。

如何更正此问题或如何将以下代码重写为递归?

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

  <xsl:template match="chapter">    
    <table>
      <tr>
        <td>
          <h2>
            <xsl:value-of select="@name"/>
          </h2>
        </td>
      </tr>
      <xsl:apply-templates select="subchapter"/>
      <xsl:apply-templates select="checklist"/>
    </table>
  </xsl:template>



  <xsl:template match="subchapter">

      <tr>
        <td>
          <h3>
            <xsl:attribute name="name">
              <xsl:value-of select="@value"/>
            </xsl:attribute>
            <xsl:value-of select="@name"/>
          </h3>
        </td>
      </tr>

      <xsl:apply-templates select="subchapter"/>
      <xsl:apply-templates select="checklist"/>

  </xsl:template>


  <xsl:template match="checklist">    
      <tr>
        <td>
          <h4>
            <xsl:attribute name="name">
              <xsl:value-of select="@value"/>
            </xsl:attribute>

            <xsl:value-of select="@name"/>

          </h4>
        </td>
      </tr>

      <xsl:apply-templates select="summary"/>

  </xsl:template>

  <xsl:template match="summary">    
      <tr>
        <td>
          <xsl:copy-of select="*"/>
        </td>
      </tr>    
  </xsl:template>

1 个答案:

答案 0 :(得分:2)

我在猜测(没有看到输入和预期的输出,我只能猜测),而不是:

<xsl:apply-templates select="subchapter"/>
<xsl:apply-templates select="checklist"/>

你想要:

<xsl:apply-templates select="subchapter | checklist"/>

如果chapter仅包含 subchapterchecklist,您可以将其缩短为:

<xsl:apply-templates/>