Merging set of elements based on a common attribute in XSLT 1.0

前端 未结 1 1863
长情又很酷
长情又很酷 2020-12-22 10:47

I m working with XSLT1.0 . My requirement is to merge set of elements based on a common attribute. I ve an xml which looks like this:



        
相关标签:
1条回答
  • 2020-12-22 11:13

    As shown in the other topic halfbit linked to, you need to use a key in order to (1) select distinct products (aka the Muenchian method) and (2) collect the values from the related group.

    Here's a little more readable (IMHO) version:

    <?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" version="1.0" encoding="UTF-8" indent="yes" />
    
    <xsl:key name="sameProduct" match="product" use="productId" />
    
    <xsl:template match="/">
    
    <!-- SELECT ONLY THE FIRST PRODUCT IN EACH GROUP -->
    <xsl:for-each select="Catalog/product[generate-id() = generate-id(key('sameProduct', productId)[1])]">
    <product>
        <productId><xsl:value-of select="productId"/></productId>
        <name><xsl:value-of select="name"/></name>
        <category>
            <!-- GET THE VALUES FROM ALL MEMBERS OF THE GROUP -->
            <xsl:for-each select="key('sameProduct', productId)">
                <xsl:value-of select="category"/>
                <xsl:if test="position() != last()">
                    <xsl:text>,</xsl:text>
                </xsl:if>
            </xsl:for-each>
        </category>
    </product>
    </xsl:for-each>
    
    </xsl:template>
    </xsl:stylesheet>
    

    If your processor is EXSLT capable, you can use the set:distinct() function instead of the Muenchian grouping.

    0 讨论(0)
提交回复
热议问题