简体   繁体   中英

grouping in xml using xslt 2.0

I have an input xml

<document>   
      <row>   
        <column1>book1</column1>     
        <column2>00290</column2>      
        <column3>asddfr</column3>  
     </row>  
   <row>  
      <column1>book1</column1>  
      <column2>00290</column2>    
      <column3>cdcd</column3>  
    </row>  
     </document>

i want an output xml as , while traversing the whole xml I need grouping and sub-grouping for each of them

<book name="Book1"> 
    <title name="asddfr" code="00290"> 
        <title name="cdcd" code="00290"> 
 </book>

This question is way too old to expect an answer. However for the benefit of others who may stumble on XSLT 2.0 grouping, below is the XSLT that will help along with the explanation.

The requirement is to group by book1 ie value in <column1> node for which XSLT 2.0 provides <xsl:for-each-group> feature.

<xsl:for-each-group select="row" group-by="column1" >

Once the grouping is done, node <book> can be created with an attribute @name having value stored in current-grouping-key() . Attribute value template ie curly braces are used to substitute the value returned.

<book name="{current-grouping-key()}">

Next step to loop within the current-group() to get the @name and @code for the <title> node.

<xsl:for-each select="current-group()">

The complete XSLT looks as below

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*"/>

    <xsl:template match="document">
        <xsl:for-each-group select="row" group-by="column1" >
            <book name="{current-grouping-key()}">
                <xsl:for-each select="current-group()">
                    <title name="{column3}" code="{column2}" />
                </xsl:for-each>
            </book>
        </xsl:for-each-group>
    </xsl:template>
</xsl:stylesheet>

And the output is

<book name="book1">
   <title name="asddfr" code="00290"/>
   <title name="cdcd" code="00290"/>
</book>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM