Grouping Nodes by hardcoding node values in XSLT

后端 未结 2 1640
渐次进展
渐次进展 2021-01-28 01:05

   
      1
      
A1 1000 <
相关标签:
2条回答
  • 2021-01-28 01:12

    If you have the option of using for-each-group, I'd definitely use that over Muenchian grouping...

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:strip-space elements="*"/>
    
      <xsl:template match="/*">
        <Output>
          <xsl:for-each-group select="Entry" group-by="substring(Details/Code,1,1)">
            <Code-group>
              <xsl:value-of select="current-grouping-key()"/>
            </Code-group>
            <Sum>
              <xsl:value-of select="sum(current-group()/Details/Value)"/>
            </Sum>
          </xsl:for-each-group>
        </Output>
      </xsl:template>
      
    </xsl:stylesheet>
    

    Fiddle: http://xsltfiddle.liberty-development.net/jxNakzX

    If you truly want to hard code the "A" -> A1, A2 and "B" -> B1, B2 mapping, you could use xsl:key and not group at all...

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:strip-space elements="*"/>
    
      <xsl:key name="A" match="Entry[Details/Code=('A1','A2')]" use="'A'"/>
      <xsl:key name="B" match="Entry[Details/Code=('B1','B2')]" use="'B'"/>
    
      <xsl:template match="/*">
        <xsl:variable name="ctx" select="."/>
        <Output>
          <xsl:for-each select="('A','B')">
            <xsl:variable name="key" select="."/>
            <Code-group>
              <xsl:value-of select="$key"/>
            </Code-group>
            <Sum>
              <xsl:value-of select="sum($ctx/key($key,$key)/Details/Value)"/>
            </Sum>
          </xsl:for-each>
        </Output>
      </xsl:template>
      
    </xsl:stylesheet>
    

    Fiddle: http://xsltfiddle.liberty-development.net/jxNakzX/1

    0 讨论(0)
  • 2021-01-28 01:31

    The hardcoding requirement is difficult to understand. Perhaps you want to do something like:

    XSLT 2.0

    <xsl:stylesheet version="2.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="entry" match="Entry" use="Details/Code"/>
    
    <xsl:template match="/root">
        <Output>
            <Code-group> A </Code-group>
            <Sum>
                <xsl:value-of select="sum(key('entry', ('A1', 'A2'))/Details/Value)" />
            </Sum>
            <Code-group> B </Code-group>
            <Sum>
                <xsl:value-of select="sum(key('entry', ('B1', 'B2'))/Details/Value)" />
            </Sum>
        </Output>
    </xsl:template>
    
    </xsl:stylesheet>
    
    0 讨论(0)
提交回复
热议问题