简体   繁体   English

使用xslt 2.0在xml中分组

[英]grouping in xml using xslt 2.0

I have an input xml 我有一个输入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 我想要一个输出xml作为,而遍历整个xml时,我需要为它们中的每一个进行分组和子分组

<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. 但是,为了使其他可能迷失XSLT 2.0分组的人受益,下面是XSLT,它将有助于进行解释。

The requirement is to group by book1 ie value in <column1> node for which XSLT 2.0 provides <xsl:for-each-group> feature. 要求是按book1分组,即XSLT 2.0为此提供了<xsl:for-each-group>功能的<column1>节点中的值。

<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() . 分组完成后,可以使用属性@name创建节点<book> ,该属性的值存储在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. 下一步,在current-group()循环获取<title>节点的@name@code

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

The complete XSLT looks as below 完整的XSLT如下所示

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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