嵌套/多级分组xslt

问题描述 投票:0回答:2

我有下面的 xml,我需要首先对请求者进行分组,然后对于每个组,我需要根据项目是否存在进行另一个分组。

<root>
<row>
    <Requester>Tim</Requester>
    <Item>A</Item>
</row>
<row>
    <Requester>Tim</Requester>
    <Item>B</Item>
</row>
<row>
    <Requester>Tim</Requester>
    <Item/>
</row>
<row>
    <Requester>Ken</Requester>
    <Item>A</Item>
</row>

如您所见,前 3 行有匹配的请求者,但 Tim 的第 3 行没有项目。所以蒂姆应该有 2 组。

我需要的输出如下所示:

<root>
<row>
    <Requester>Tim</Requester>
    <Line>
        <Item>A</Item>      ---> Grouped together because Item exists. Item name may not match
        <item>B</item>
    </Line>
</row>
<row>
    <Requester>Tim</Requester>
    <Line>
        <Item/>        --> Separate group because there is no Item 
    </Line>
</row>
<row>
    <Requester>Ken</Requester>
    <Line>
        <Item>A</Item>
    </Line>
</row>

到目前为止我能够构建的xslt:

    <xsl:template match="/">
    <root>
        <xsl:for-each-group select="root/row" group-by="Requester">
            <row>
                <Requester>
                    <xsl:value-of select="Requester[position()=1]"/>
                </Requester>
                <xsl:for-each select="current-group()">
                    <Line>
                        <Item>                        
                            <xsl:value-of select="Item"/>
                        </Item>
                    </Line>
                </xsl:for-each>
            </row>
        </xsl:for-each-group>
    </root>    
</xsl:template>
xslt xslt-grouping
2个回答
0
投票

尝试:

XSLT 3.0

<xsl:stylesheet version="3.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/root">
    <root>
        <xsl:for-each-group select="row" group-by="Requester, exists(Item/text())" composite="yes">
            <row>
                <xsl:copy-of select="Requester"/>
                <Line>
                    <xsl:copy-of select="current-group()/Item"/>
                </Line>
            </row>
        </xsl:for-each-group>
    </root>    
</xsl:template>

</xsl:stylesheet>

0
投票

我想你想要

  <xsl:template match="root">
    <xsl:copy>
      <xsl:for-each-group select="row" group-by="Requester, exists(Item/node())" composite="yes">
        <xsl:copy>
          <xsl:copy-of select="Requester"/>
          <Line>
            <xsl:copy-of select="current-group()/Item"/>
          </Line>
        </xsl:copy>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>
© www.soinside.com 2019 - 2024. All rights reserved.