XSLT: add up number and print subtotal multiple times

前端 未结 4 1222
北荒
北荒 2021-01-16 14:29

I\'m a beginner in XSLT and figured out that I cannot just add up numbers to a variable and change its value in any way.

I have a XML document with a list of numbers

4条回答
  •  粉色の甜心
    2021-01-16 15:23

    Just as a different solution to the grouping suggested as comment - you could also use match patterns to get the sums:

    
    
    
    
    
      
    
    
      
      
      
         #
         
        #
         
      
    
    

    When applied to your input XML this produces the output

    189.5
    1.5
    #191#
    9.5
    11
    10
    #30.5#
    

    The template matching field[@type='num'] prints the value and adds a newline, and the template matching entry[field[@type='summary']] uses the variable

    
    

    to check how many previous fields of the type summary occured. Then only the sum of all values of entries of the type num with the same amount of preceding summary fields is printed:

    
    

    Update: To explain in more detail how this works as requested: In the template matching entry[field[@type='summary']] the variable sumCount counts all previous entries that have a field of type summary:

    count(preceding-sibling::entry[field[@type='summary']])
    

    So when the template matches the first summary field, the value of sumCount is 0, and when matching the second summary field, sumCount is 1.
    The second line using the sum function

    sum(
        preceding-sibling::entry
         [
          count(preceding-sibling::entry[field[@type='summary']]) = 
          $sumCount
         ]
         /field[@type='num']/@value
       )
    

    sums all field[@type='num']/@value for all previous (preceding) entries that have the same amount of previous fields of type summary as the current field of type summary:

    count(preceding-sibling::entry[field[@type='summary']]) = $sumCount
    

    So when the second summary is matched, only the values of the num fields with the values 9.5, 10 and 11 will be summarized as they have the same amount of previous summary fields as the current summary field.
    For the num fields with the values 189.5 and 1.5,

    count(preceding-sibling::entry[field[@type='summary']]) 
    

    is 0, so these fields are omitted in the sum function.

提交回复
热议问题