2011-05-11 54 views
1

我的XSL文件深度更改標題級別:如何通過XSLT基於XML格式

 ... 
     <div> 

      <xsl:choose> 
      <xsl:when test="count(ancestor::node()) = 1"> 
       <h2> 
      </xsl:when> 
      <xsl:when test="count(ancestor::node()) = 2"> 
       <h3> 
      </xsl:when> 
      </xsl:choose> 

      <xsl:attribute name="id"> 
       <xsl:value-of select="@id" /> 
      </xsl:attribute> 
      <xsl:copy-of select="title/node()"/> 

      <xsl:choose> 
      <xsl:when test="count(ancestor::node()) = 1"> 
       </h2> 
      </xsl:when> 
      <xsl:when test="count(ancestor::node()) = 2"> 
       </h3> 
      </xsl:when> 
      </xsl:choose> 

     </div> 

我知道這是不允許拆標籤H2 ....../H2,H3 .../H3喜歡這個。

但是如何正確地做到這一點?

回答

2

你可以用遞歸模板做到這一點,並動態地生成標題元素。

例如,該輸入XML:

<input> 
    <level id="1"> 
    <title>first</title> 
    <level id="2"> 
     <title>second</title> 
     <level id="3"> 
     <title>third</title> 
     </level> 
    </level> 
    </level> 
</input> 

這個XSLT處理:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl"> 
<xsl:output omit-xml-declaration="yes" indent="yes" method="html"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="level"> 
    <xsl:variable name="level" select="count(ancestor-or-self::level) + 1"/> 

    <xsl:element name="h{$level}"> 
    <xsl:attribute name="id"> 
     <xsl:value-of select="@id"/> 
    </xsl:attribute> 
    <xsl:copy-of select="title/node()"/> 
    </xsl:element> 

    <xsl:apply-templates select="level"/> 
</xsl:template> 
</xsl:stylesheet> 

給出了以下HTML:

<h2 id="1">first</h2> 
<h3 id="2">second</h3> 
<h4 id="3">third</h4> 
+0

謝謝!我做了像thsi 我不知道xsl:element命令:-) – podeig 2011-05-11 10:43:41

0

你可以使用

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

<xsl:template match="/*/div"> 
    <h2><xsl:apply-templates/></h2> 
</xsl:template> 

<xsl:template match="/*/*/div"> 
    <h3><xsl:apply-templates/></h3> 
</xsl:template>