【发布时间】:2013-09-03 00:17:34
【问题描述】:
有人可以帮我解决这个问题吗?
这是我的 XML -
<grandparent>
<parent>
<child>apple</child>
</parent>
<parent>
<child>apple</child>
<child>orange</child>
<child>apple</child>
<child>apple</child>
<child>apple</child>
</parent>
<parent>
<child>pear</child>
<child>apple</child>
<child>pear</child>
<child>pear</child>
</parent>
</granparent>
我有一个模板,我将 parent 传递给它,它会吐出所有子标签,但我希望它只吐出唯一的子值。
我进行了搜索,每个人使用密钥的建议似乎都不起作用,因为它似乎只获得祖父母范围内的唯一值,而不是父母范围内的唯一值。
这就是我所拥有的-
<xsl:template name="uniqueChildren">
<xsl:param name="parent" />
<xsl:for-each select="$parent/child">
<xsl:value-of select="." />
</xsl:for-each>
</xsl:template>
目前显示 -
apple
apple orange apple apple apple
pear apple pear pear
我尝试按键时的代码 -
<xsl:key name="children" match="child" use="." />
<xsl:template name="uniqueChildren">
<xsl:param name="parent" />
<xsl:for-each select="$parent/child[generate-id() = generate-id(key('children', .)[1])]">
<xsl:value-of select="." />
</xsl:for-each>
</xsl:template>
当我尝试使用它显示的键时 -
apple
orange
pear
我希望它显示什么 -
apple
apple orange
pear apple
【问题讨论】:
-
“当我尝试使用密钥时” - 你能展示一下你在这种情况下使用的 XSLT 吗?这可能只是稍微调整键定义以考虑父元素的情况。
-
我已经包含了上面的关键示例,谢谢。
-
进一步查看,key 是顶级元素,所以在模板中创建 key 也不起作用,似乎破坏了整个页面......