如何在 XSLT 1.0 中聚合节点? [英] How to aggregate nodes in XSLT 1.0?

查看:23
本文介绍了如何在 XSLT 1.0 中聚合节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要使用 XSLT 1.0 聚合一系列节点,但我总是很难找到一个干净的解决方案.

I often need to aggregate a sequence of nodes using XSLT 1.0 but I always struggle to find a clean solution.

这是一个典型的例子;

输入

<x>Foo/Red</x>
<x>Foo/Green</x>
<x>Foo/Blue</x>
<x>Bar/Hello</x>
<x>Bar/World</x>

期望输出

<y s="Foo">Red, Green, Blue</y>
<y s="Bar">Hello, World</y>

我总是被这类问题搞得一团糟.是否有针对上述问题的优雅 XSLT 1.0 解决方案?

I always end up in a mess with this type of problem. Is there an elegant XSLT 1.0 solution to the above?

我正在使用 PHPlibxslt 所以我确实可以在必要时使用 exslt:node-set() 函数.

I'm using PHP's libxslt so I do have the exslt:node-set() function available to use if necessary.

推荐答案

这里是根据您的示例改编的 muenchian 分组.有关更多信息,请查看例如此处.如果您了解它的工作原理并尝试使其适应不断变化的分组问题,它就会变得非常方便.

Here an adaption of muenchian grouping to your example. For more info look e.g. here. If you ones have understand how it work and tried to adapt it to changing grouping issues it becomes quite handy.

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="kXprev" match="x" use="substring-before(text(),'/')"/>

    <xsl:template name="y">
        <xsl:param name="s" />
        <y s="{$s}">
            <xsl:for-each select="key('kXprev', $s)">
                <xsl:if test="position()>1" >
                    <xsl:text> </xsl:text>
                </xsl:if>
                <xsl:value-of select="substring-after(text(),'/')"/>
            </xsl:for-each>
        </y>

    </xsl:template>
    <xsl:template match="/*">
        <out>
            <xsl:for-each select="x[count( . | key('kXprev',substring-before(text(),'/') )[1] ) =1]" >
                <xsl:call-template name="y">
                    <xsl:with-param name="s" select="substring-before(text(),'/') "/>
                </xsl:call-template>
            </xsl:for-each>
        </out>
    </xsl:template>
</xsl:stylesheet>

这篇关于如何在 XSLT 1.0 中聚合节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆