开发者

xslt 1.0 - transform nodes before specific element into other element

i have following Input:

<p>
    XYZZ
    <nl/>
    DEF
    <process>gggg</process>
    KKK
    <nl/>
    JKLK
    <nl/>
    QQQQ
</p>

I need each node seprated by element <nl/> to be output 开发者_如何学编程in element <title>:

<p>      
    <title>XYZZ</title>  
    <title>
        DEF<process>gggg</process>KKK  
    </title>  
    <title>JKLK</title>  
    <title>QQQQ</title>  
</p>

` Please suggest me the way to get the specified output.


This transformation:

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

 <xsl:key  name="kFollowing" match="/*/node()[not(self::nl)]"
  use="generate-id(preceding-sibling::nl[1])"/>

 <xsl:key  name="kPreceding" match="/*/node()[not(self::nl)]"
  use="generate-id(following-sibling::nl[1])"/>

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

    <xsl:template match="/*">
     <xsl:copy>
      <xsl:apply-templates select="@*|nl"/>
     </xsl:copy>
    </xsl:template>

    <xsl:template match="nl" name="groupFollowing">
      <title>
       <xsl:apply-templates select="key('kFollowing',generate-id())"/>
      </title>
    </xsl:template>

    <xsl:template match="nl[1]">
     <title>
       <xsl:apply-templates select="key('kPreceding',generate-id())"/>
     </title>
     <xsl:call-template name="groupFollowing"/>
    </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<p>
       XYZZ
       <nl/>
       DEF
       <process> gggg </process>
       KKK
       <nl/>
       JKLK
       <nl/>
       QQQQ
</p>

produces the wanted, correct result:

<p>
   <title>
       XYZZ
       </title>
   <title>
       DEF
       <process> gggg </process>
       KKK
       </title>
   <title>
       JKLK
       </title>
   <title>
       QQQQ
</title>
</p>

Do note:

  1. The identity rule is used to copy nodes "as-is".

  2. There are specific templates matching the top element, the first nl child of the top element and any nl child of the top element.

  3. Two keys are defined that select all non-nl nodes that immediately-precede an nl element and all nodes that immediately-follow an nl element.

  4. An nl element is replaced by a title element and all immediately-following non-nl nodes are processed and the result is put into this title element.

  5. For the first (child of its parent) nl element there is an initial step in which a title element is added and all immediately-preceding non-nl nodes are processed and the result is put into this title element. Then the processing in step 4. above is performed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜