XSLT to sum product of two attributes

前端 未结 6 1128
花落未央
花落未央 2021-01-12 16:53

I have the following XML source structure:


    
    

        
6条回答
  •  时光说笑
    2021-01-12 17:18

    In XSLT 1.0 the use of FXSL makes such problems easy to solve:

    
     
     
    
          
    
         
          
        
    
        
          
    
          
              
                
                
                
              
          
    
          
        
    
        
        
         
         
    
         
        
    
    

    When this transformation is applied on the originally posted source XML document, the correct result is produced:

    310

    In XSLT 2.0 the same solution using FXSL 2.0 can be expressed by an XPath one-liner:

    sum(f:zipWith(f:multiply(),
              /*/*[xs:decimal(@repid) eq 1]/@amount/xs:decimal(.),
              /*/*[xs:decimal(@repid) eq 1]/@rate/xs:decimal(.)
              )
         )
    

    The whole transformation:

    
     
     
    
     
     
    
     
       
     
    
    

    Again, this transformation produces the correct answer:

    310

    Note the following:

    1. The f:zipWith() function takes as arguments a function fun() (of two arguments) and two lists of items having the same length. It produces a new list of the same length, whose items are the result of the pair-wise application of fun() on the corresponding k-th items of the two lists.

    2. f:zipWith() as in the expression takes the function f:multiply() and two sequences of corresponding "ammount" and "rate" attributes. The sesult is a sequence, each item of which is the product of the corresponding "ammount" and "rate".

    3. Finally, the sum of this sequence is produced.

    4. There is no need to write an explicit recursion and it is also guaranteed that the behind-the scenes recursion used within f:zipWith() is never going to crash (for all practical cases) with "stack overflow"

提交回复
热议问题