2011-04-27 50 views
1

亲爱的社区, 各个元素,我想变换具有这种格式的XML初始:XSLT:如何分类分别位于同一水平

<h2>title1</h2> 
<div>sometext1</div> 
<div>sometext2</div> 
<h2>title2</h2> 
<div>sometext3</div> 
<div>sometext4</div> 
<h2>title3</h2> 
<div>sometext5</div> 
<div>sometext6</div> 

<cat name="title1"> 
<div>sometext1</div> 
<div>sometext2</div> 
</cat> 
<cat name="title2"> 
<div>sometext3</div> 
<div>sometext4</div> 
</cat> 
<cat name="title3"> 
<div>sometext5</div> 
<div>sometext6</div> 
</cat> 

我试图执行double for-each并创建一个变量来保存“select”选项来执行inner for-each,但似乎需要使用node-set()函数。即使我尝试包含它,它也不起作用。你有没有想过如何解决这个问题,使用XSLT 1.0,最好不使用任何其他名称空间?

+0

向我们展示您的变换 – ThomasRS 2011-04-27 16:20:16

+0

[使用XSLT合并相邻兄弟节点]的可能副本(http://stackoverflow.com/questions/2091951/merge-adjacent-sibling-nodes-with-xslt) – 2011-04-27 17:10:59

回答

0

以下是一种不依赖于嵌套循环的方法。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

    <xsl:key name="x" match="div" use="preceding-sibling::h2[1]"/> 

    <xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()[not(name()='div')]"/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="h2"> 
    <cat name="{text()}"> 
     <xsl:apply-templates select="key('x',.)"/> 
    </cat> 
    </xsl:template> 

</xsl:stylesheet> 

它首先建立一个索引(xsl:key),它将每个div映射到紧邻的前一个h2。然后我们有一个简单的标识转换,可以跳过div条目。对于遇到的每个h2,我们生成<cat>,然后输出从该h2索引的<div...>标签。