Xslt递归转换

时间:2016-11-22 21:54:57

标签: xml xslt xpath grouping siblings

我已经尝试过所有方式,但没有结果。如何使用XSLT转换像这样的XML:

NoFill

在这样的XML中?

<root>
     <row>topic</row>
     <row>Topic1</row>
     <row>words</row>
     <row>word1</row>
     <row>word2</row>
     <row>word3</row>
     <row>words</row>
     <row>word4</row>
     <row>word5</row>
     <row>word6</row>
     <row>topic</row>
     <row>Topic2</row>
     <row>words</row>
     <row>word7</row>
     <row>word8</row>
     <row>word9</row>
     <row>topic</row>
     <row>Topic3</row>
     <row>words</row>
     <row>word10</row>
     <row>word11</row>
     <row>word12</row>
</root>

'主题'和'单词'值经常出现在XML中,我会先按主题分组,然后在每个主题组中按“单词”分组......

非常感谢提前!

1 个答案:

答案 0 :(得分:1)

在XSLT 2.0中,您可以这么简单:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="root">
    <xsl:copy>
        <xsl:for-each-group select="row" group-starting-with="row[.='topic']">
            <topic>
                <xsl:value-of select="current-group()[2]"/>
                <words>
                    <xsl:value-of select="current-group()[position() gt 3]" separator=""/>
                </words>
            </topic>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>