嘿,我有一个场景,我有一个xml结构,比如
<deftms>
<tn>abc</tn>
<td>xyz</td>
<tn>abc1</tn>
<td>xyz1</td>
<tn>abc2</tn>
<td>xyz2</td>
</deftms>
要将其转换为:
<deftms>
<newtms>
<tn>abc</tn>
<td>xyz</td>
</newtms>
<newtms>
<tn>abc1</tn>
<td>xyz1</td>
</newtms>
<newtms>
<tn>abc2</tn>
<td>xyz2</td>
</newtms>
</deftms>
我使用以下转换XSL代码来实现输出
<xsl:template name = "deftms">
<deftms>
<xsl:for-each select="//deftms/tn">
<xsl:variable name="tn"><xsl:value-of select="current()" /></xsl:variable>
<xsl:variable name="td"><xsl:value-of select="(current())" /></xsl:variable>
<newtms>
<tn><xsl:copy-of select="$tn" /></tn>
<td><xsl:copy-of select="$td" /></td>
</newtms>
</xsl:for-each>
</deftms>
</xsl:template>
谁知道?
在for-each
中,position()
功能将为您提供所需的内容。在for-each
选择的节点列表中,它返回当前正在处理的节点的(基于1的)索引——非正式的"迭代数"(尽管for-each
不一定需要作为处理器内的循环来实现)。
<xsl:template name = "deftms">
<deftms>
<xsl:for-each select="//deftms/tn">
<xsl:variable name="pos" select="position()" />
<xsl:variable name="td" select="../td[$pos]" />
<newtms>
<tn><xsl:copy-of select="." /></tn>
<td><xsl:copy-of select="$td" /></td>
</newtms>
</xsl:for-each>
</deftms>
</xsl:template>
尝试:
<xsl:template name = "deftms">
<deftms>
<xsl:for-each select="tn">
<newtms>
<xsl:copy-of select=". | following-sibing::td[1]" />
</newtms>
</xsl:for-each>
</deftms>
</xsl:template>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="deftms" name ="ParentCopy">
<xsl:copy>
<xsl:param name="LoopCountA">1</xsl:param>
<xsl:variable name = "CountDate" >
<xsl:value-of select = "count(tn)"/>
</xsl:variable>
<xsl:choose>
<xsl:when test = " $LoopCountA <= $CountDate " >
<newtms>
<xsl:copy-of select="tn[position()= $LoopCountA]"/>
<xsl:copy-of select ="td[position()= $LoopCountA]"/>
</newtms>
<xsl:call-template name="ParentCopy">
<xsl:with-param name="LoopCountA">
<xsl:value-of select="$LoopCountA + 1"/>
</xsl:with-param>
</xsl:call-template>
</xsl:when>
</xsl:choose>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>