XSL Multiple search and replace function

后端 未结 4 1530
天涯浪人
天涯浪人 2020-12-10 09:13

I am attempting to use the XSL translate() function to create something like a search and replace function as follows:



        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 09:52

    The translate() function can only replace a single character with another single character (or with the empty character (delete)). Thus it cannot solve the problem of string replacement.

    Here is a complete XSLT 1.0 solution to the multiple-replace problem:

    
        
        
    
        
            
                
    
                
    quick slow fox elephant brown white

    when this transformation is applied on the following XML document:

    The quick
    brown fox
    

    the wanted, correct result is produced:

    The slow
    white elephant

    Explanation:

    1. A named template that calls itself recursively is used.

    2. All multiple replacement pattern --> replacement pairs are provided in a single external parameter, which for convenience here is specified inline as the global-level element .

    3. The recursion takes every single character in the source string (from left to right) and finds the first pattern that starts with this character at this position in the string.

    4. The replacement can be not only a string but also any node. In this specific case we are replacing every NL character with a
      element.

提交回复
热议问题