Check if a string is null or empty in XSLT

前端 未结 14 1217
梦毁少年i
梦毁少年i 2020-11-27 09:12

How can I check if a value is null or empty with XSL?

For example, if categoryName is empty? I\'m using a when choosing construct.

For

14条回答
  •  鱼传尺愫
    2020-11-27 09:44

    I know this question is old, but between all the answers, I miss one that is a common approach for this use-case in XSLT development.

    I am imagining that the missing code from the OP looks something like this:

    
        
            
                
            
            
                
            
        
    
    

    And that the input looks something like this:

    
        
           Books
        
        
           Magazines
           Periodicals
           Journals
        
        
            
        
        
            
        
        
    
    

    I.e., I assume there can be zero, empty, single or multiple categoryName elements. To deal with all these cases using xsl:choose-style constructs, or in other words, imperatively, is quickly getting messy (even more so if elements can be at different levels!). A typical programming idiom in XSLT is using templates (hence the T in XSLT), which is declarative programming, not imperative (you don't tell the processor what to do, you just tell what you want output if certain conditions are met). For this use-case, that can look something like the following:

    
    
        
    
    
    
    
        Category: Other
    
    
    
    
        Category: 
        
    
    

    This works (with any XSLT version), because the first one above has a higher precedence (it has a predicate). The "fall-through" matching template, the second one, catches anything that is not valid. The third one then takes care of outputting the categoryName value in a proper way.

    Note that in this scenario there is no need to specifially match categories or category, because the processor will automatically process all children, unless we tell it otherwise (in this example, the second and third template do not further process the children, because there is no xsl:apply-templates in them).

    This approach is more easily extendible then the imperative approach, because it automically deals with multiple categories and it can be expanded for other elements or exceptions by just adding another matching template. Programming without if-branches.

    Note: there is no such thing as null in XML. There is xsi:nil, but that is rarely used, especially rarely in untyped scenarios without a schema of some sort.

提交回复
热议问题