我有一个XML文件,其中包含节点列表MOVIMENTO,我需要使用XSLT1.0按子标记SIGLA的值对这些节点进行分组。
<RESULT>
<MOVIMENTO> <!-- MOVIMENTO: nodes to cicle into -->
<INFO>
<MOV_AREA>10</MOV_AREA>
</INFO>
<ARTICOLI>
<ARTICOLO>
<SIGLA>80069</SIGLA> <!-- SIGLA: nodes to group by distinct value -->
<UM>NR</UM>
<QTA_CONS>1,00</QTA_CONS>
</ARTICOLO>
</ARTICOLI>
</MOVIMENTO>
<MOVIMENTO>
<INFO>
<MOV_AREA>13</MOV_AREA>
</INFO>
<ARTICOLI>
<ARTICOLO>
<SIGLA>80069</SIGLA>
<UM>NR</UM>
<QTA_CONS>1,00</QTA_CONS>
</ARTICOLO>
</ARTICOLI>
</MOVIMENTO>
<MOVIMENTO>
<INFO>
<MOV_AREA>14</MOV_AREA>
</INFO>
<ARTICOLI>
<ARTICOLO>
<SIGLA>77586</SIGLA>
<UM>NR</UM>
<QTA_CONS>1,00</QTA_CONS>
</ARTICOLO>
</ARTICOLI>
</MOVIMENTO>
</RESULT>
我尝试了很多基于网络上的例子的解决方案,但没有一个对我来说是正确的。有人能帮我吗?下面的代码,我正在使用:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:key name="groups" match="ARTICOLO" use="SIGLA" />
<xsl:template match="RESULT">
<xsl:apply-templates select="MOVIMENTO/ARTICOLI/ARTICOLO[generate-id() = generate-id(key('groups', SIGLA)[1])]"/>
</xsl:template>
<xsl:template match="ARTICOLO">
<xsl:for-each select="key('groups', SIGLA)">
SIGLA: <xsl:value-of select="normalize-space(SIGLA)"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
XSLT代码中需要进行一些调整。密钥需要更改为
<xsl:key name="groups" match="MOVIMENTO" use="ARTICOLI/ARTICOLO/SIGLA" />
可以使用identity transform
模板按原样复制要输出的元素,然后应用分组。
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
匹配分组元素的<MOVIMENTO>
模板,然后循环遍历不同元素的键。
<xsl:template match="MOVIMENTO[generate-id() = generate-id(key('groups', ARTICOLI/ARTICOLO/SIGLA)[1])]">
<xsl:copy>
<xsl:for-each select="key('groups', ARTICOLI/ARTICOLO/SIGLA)">
<xsl:apply-templates select="INFO" />
</xsl:for-each>
<xsl:apply-templates select="key('groups', ARTICOLI/ARTICOLO/SIGLA)[1]/ARTICOLI" />
</xsl:copy>
</xsl:template>
最后,对于任何其他<MOVIMENTO>
节点,不执行任何操作。
<xsl:template match="MOVIMENTO" />
输出低于
<RESULT>
<MOVIMENTO>
<INFO>
<MOV_AREA>10</MOV_AREA>
</INFO>
<INFO>
<MOV_AREA>13</MOV_AREA>
</INFO>
<ARTICOLI>
<ARTICOLO>
<SIGLA>80069</SIGLA>
<UM>NR</UM>
<QTA_CONS>1,00</QTA_CONS>
</ARTICOLO>
</ARTICOLI>
</MOVIMENTO>
<MOVIMENTO>
<INFO>
<MOV_AREA>14</MOV_AREA>
</INFO>
<ARTICOLI>
<ARTICOLO>
<SIGLA>77586</SIGLA>
<UM>NR</UM>
<QTA_CONS>1,00</QTA_CONS>
</ARTICOLO>
</ARTICOLI>
</MOVIMENTO>
</RESULT>