我有两个嵌套循环。第一个循环是获取不同的值,并在第二个循环中进行比较。在第二个循环中,我给出了position((,它的顺序为1,2,3,但我希望它在第一次迭代中显示为1,1,1,在第二次迭代中出现为2,2,2,在第三次迭代中呈现为3,3,3,依此类推
XML:
<root>
<Items>
<Item>
<ItemCode>12345</ItemCode>
<ItemColor>Red</ItemColor>
<Weight>1Kg</Weight>
</Item>
<Item>
<ItemCode>19087</ItemCode>
<ItemColor>Blue</ItemColor>
<Weight>1Kg</Weight>
</Item>
</Items>
<Items>
<Item>
<ItemCode>12345</ItemCode>
<ItemColor>Yellow</ItemColor>
<Weight>1Kg</Weight>
</Item>
<Item>
<ItemCode>19087</ItemCode>
<ItemColor>Green</ItemColor>
<Weight>1Kg</Weight>
</Item>
</Items>
</root>
所需输出:
12345
1.Red
1.Yellow
19087
2.Blue
2.Green
(Or)
1.12345
Red
Yellow
2.19087
Blue
Green
代码:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="check" match="Items" use="ItemCode" />
<xsl:template match="root/Items">
<xsl:for-each select="Item[count(. | key('check', ItemCode)[1]) = 1]">
<xsl:value-of select="ItemCode"/>
<xsl:for-each select="key('check', ItemCode)">
<xsl:value-of select="position()"/>
<xsl:value-of select="ItemColor"/>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
我正在使用xslt-1.0非常感谢你的帮助。非常感谢。
以下样式表:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8"/>
<xsl:key name="item-by-code" match="Item" use="ItemCode"/>
<xsl:template match="/root">
<xsl:for-each select="Items/Item[count(. | key('item-by-code', ItemCode)[1]) = 1]">
<xsl:value-of select="position()"/>
<xsl:text>.</xsl:text>
<xsl:value-of select="ItemCode"/>
<xsl:for-each select="key('item-by-code', ItemCode)">
<xsl:text> </xsl:text>
<xsl:value-of select="ItemColor"/>
</xsl:for-each>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
当应用于您的输入示例时,将返回:
结果
1.12345
Red
Yellow
2.19087
Blue
Green
或者,你可以做:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8"/>
<xsl:key name="item-by-code" match="Item" use="ItemCode"/>
<xsl:template match="/root">
<xsl:for-each select="Items/Item[count(. | key('item-by-code', ItemCode)[1]) = 1]">
<xsl:variable name="i" select="position()" />
<xsl:value-of select="ItemCode"/>
<xsl:text> </xsl:text>
<xsl:for-each select="key('item-by-code', ItemCode)">
<xsl:value-of select="$i"/>
<xsl:text>.</xsl:text>
<xsl:value-of select="ItemColor"/>
<xsl:text> </xsl:text>
</xsl:for-each>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
获取:
12345
1.Red
1.Yellow
19087
2.Blue
2.Green