Aggregate-function for sum and product in XPath

前端 未结 3 1239
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 05:03

Similar to this question (http://stackoverflow.com/q/1333558/948404) I want to use XPath to calculate a sum over products in a structure like this:

         


        
3条回答
  •  独厮守ぢ
    2021-01-21 05:21

    Use this XPath 2.0 expression:

    sum(/items/item/(value * quantity))
    

    Here is an XSLT 2.0 transformation as verification:

    
        
    
        
            
        
    
    

    When this transformation is applied on the provided XML document:

    
        
            1.0
            3
        
        
            2.5
            2
        
        
    
    

    the XPath expression is evaluated and the result of this evaluation is output:

    8
    

    Explanation:

    In XPath 2.0 it is legal for a location step to be

    /(expression),

    or even

    /someFunction(argumentList)


    II. XSLT 1.0 solution:

    
     
    
     
      
        
      
     
    
     
       
       
    
       
        
         
        
        
         
          
          
         
        
       
     
    
    

    when this transformation is applied on the provided XML document (above), again the wanted, correct result is produced:

    8
    

    Do note: Such kind of problems are easy to solve using the FXSL library. The template to call is transform-and-sum .

提交回复
热议问题