2012-01-30 70 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>