2012-01-30 40 views
1

我需要一些關於我正在編寫的xslt的幫助。以下是我的源代碼xml。使用XSLT版本1.0的節點分組

<document> 
    <content1></content1> 
    <content2></content2> 
    <Br/> 
    <content3></content3> 
    <content4></content4> 
    <Br/> 
    <content5></content5> 
    <content6></content6> 
</document> 

下面是輸出的結構,我打算創建:

<document> 
    <p> 
     <content1></content1> 
     <content2></content2> 
    </p> 
    <p> 
     <content3></content3> 
     <content4></content4> 
    </p> 
    <p> 
     <content5></content5> 
     <content6></content6> 
    </p> 
</document> 

我的問題是,我怎麼組的內容,並把它包在一個「<p>」標籤,每當我看到「<Br>」tag?

謝謝!

回答

1

使用Muenchian法一羣兒童document可以通過第一前Br

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output omit-xml-declaration="yes" indent="yes"/> 
    <xsl:strip-space elements="*"/> 
    <xsl:key name="byPosition" match="/document/*[not(self::Br)]" 
      use="generate-id(preceding-sibling::Br[1])"/> 
    <xsl:template match="@*|node()" name="identity" priority="-5"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="/document/*[not(self::Br) and 
      generate-id()=generate-id(key('byPosition', 
           generate-id(preceding-sibling::Br[1]))[1])]"> 
     <p><xsl:copy-of 
       select="key('byPosition', 
          generate-id(preceding-sibling::Br[1]))"/></p> 
    </xsl:template> 
    <xsl:template match="/document/*" priority="-3"/> 
</xsl:stylesheet> 

說明:

<xsl:key name="byPosition" match="/document/*[not(self::Br)]" 
     use="generate-id(preceding-sibling::Br[1])"/> 
首先,項基於其第一在前 Br元件上在 key分組

身份轉換用於通過不變的方式複製大多數節點:

<xsl:template match="@*|node()" name="identity" priority="-5"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

然後我們相匹配的是其key的第一個此類項目的document所有的孩子:

<xsl:template match="document/*[not(self::Br) and 
      generate-id()=generate-id(key('byPosition', 
           generate-id(preceding-sibling::Br[1]))[1])]"> 

...和使用,作爲在該點複製由key分組的所有項目:

<xsl:copy-of select="key('byPosition', 
          generate-id(preceding-sibling::Br[1]))"/> 
1

這XSLT 1.0爲您提供了預期的結果:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0"> 
    <xsl:output indent="yes"/> 
    <xsl:strip-space elements="*"/> 
    <xsl:key name="parag" match="document/*[not(self::Br)]" use="count(following-sibling::Br)"/> 
    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="document/*[not(self::Br) and not(position()=1)]"/> 
    <xsl:template match="Br|document/*[position()=1]"> 
     <p> 
      <xsl:for-each select="key('parag',count(following-sibling::Br))"> 
       <xsl:copy> 
        <xsl:apply-templates select="node()|@*"/>      
       </xsl:copy> 
      </xsl:for-each> 
     </p> 
    </xsl:template> 
</xsl:stylesheet>