【发布时间】:2020-02-02 11:56:11
【问题描述】:
我是初学者,我正在尝试使用 XSLT 1.0 根据类似类别对 XML 输入进行分组。这是包含类别和位置的输入 xml。输出必须将所有具有相同类别的元素分组并列出唯一位置:
<?xml version="1.0" ?>
<Data>
<Row>
<id>123</id>
<location>/example/games/data.php</location>
<category>gamedata</category>
</Row>
<Row>
<id>456</id>
<location>/example/games/data.php</location>
<category>gamedata</category>
</Row>
<Row>
<id>789</id>
<location>/example/games/score.php</location>
<category>gamedata</category>
</Row>
<Row>
<id>888</id>
<location>/example/games/title.php</location>
<category>gametitle</category>
</Row>
<Row>
<id>777</id>
<location>/example/games/title.php</location>
<category>gametitle</category>
</Row>
<Row>
<id>999</id>
<location>/example/score/title.php</location>
<category>gametitle</category>
</Row>
</Data>
寻找输出(仅列出按类别分组的唯一位置):
<project>
<item>
<data>
<category>gamedata</category>
<id>456</id>
<id>789</id>
<id>123</id>
<location>/example/games/data.php</location>
<location>/example/games/score.php</location>
</data>
<data> <category>gametitle</category>
<id>888</id>
<id>777</id>
<id>999</id>
<location>/example/games/title.php</location>
<location>/example/score/title.php</location>
</data>
</item></project>
到目前为止我所尝试的:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="keyCategory" match="Row" use="category"/>
<xsl:template match="/">
<project xmlns="xyz.com">
<item >
<name lang="en">Example</name>
<xsl:for-each select="//Row[generate-id(.) = generate-id(key('keyCategory', category)[1])]">
<xsl:for-each select="key('keyCategory', category)">
<data>
<category><xsl:value-of select="category"/></category>
<id><xsl:value-of select="id"/></id>
<location><xsl:value-of select="location"/></location></data>
</xsl:for-each>
</xsl:for-each>
</item>
</project>
我实际上得到了什么:
<project>
<item>
<data>
<category>gamedata</category>
<id>456</id>
<location>/example/games/data.php</location>
</data>
<data>
<category>gamedata</category>
<id>789</id>
<location>/example/games/score.php</location>
</data>
<data>
<category>gamedata</category>
<id>789</id>
<location>/example/games/score.php</location>
</data>
<data>
<category>gamedata</category>
<id>123</id>
<location>/example/games/data.php</location>
</data>
<data>
<category>gametitle</category>
<id>888</id>
<location>/example/games/title.php</location>
</data>
<data>
<category>gametitle</category>
<id>777</id>
<location>/example/games/title.php</location>
</data>
<data>
<category>gametitle</category>
<id>999</id>
<location>/example/score/title.php</location>
</data>
</item></project>
【问题讨论】:
-
如果你想对分组的元素进行分组和包装,那么显然你的包装器(例如
data)需要在<xsl:for-each select="//Row[generate-id(.) = generate-id(key('keyCategory', category)[1])]">内部使用,例如<xsl:for-each select="//Row[generate-id(.) = generate-id(key('keyCategory', category)[1])]"><data>...</data></xsl:for-each>。如果您还想识别每个组中的唯一位置,那么您需要第二个密钥或一些特定于处理器的扩展方法。 -
@MartinHonnen 非常感谢,现在按照您的建议工作。
标签: xml xslt xslt-1.0 xslt-grouping