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:
The identity rule is used to copy nodes "as-is".
There are specific templates matching the top element, the first
nl
child of the top element and anynl
child of the top element.Two keys are defined that select all non-
nl
nodes that immediately-precede annl
element and all nodes that immediately-follow annl
element.An
nl
element is replaced by atitle
element and all immediately-following non-nl
nodes are processed and the result is put into thistitle
element.For the first (child of its parent)
nl
element there is an initial step in which atitle
element is added and all immediately-preceding non-nl
nodes are processed and the result is put into thistitle
element. Then the processing in step 4. above is performed.
精彩评论