XSLT - Using substring with copy-of to preserve inner HTML tags

后端 未结 2 1966
野的像风
野的像风 2021-01-06 18:02

I have some XML like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.Nulla vel mauris metus. E

2条回答
  •  佛祖请我去吃肉
    2021-01-06 18:34

    Here is another approach in XSLT 1.0, without having to use the node-set extension:

      
        
        
          
          
            
            
          
        
      
    
      
        
        
      
    
      
        
        
        
          
          
            
          
          
          
            
              
              
            
          
        
      
    

    Basically this is the identity template, with copying of the child nodes offloaded to a recursive template which takes care of keeping to the maximum string length, plus a separate template for text nodes, truncating them to the maximum length.

    You can invoke this for the sample input as follows:

    
      
      
    
    

    Follow-up: Splitting the story

    For the follow up question of splitting the story into two pieces after the first break or paragraph end after N characters, I'll go ahead and make the simplifying assumption that you want to consider splitting only after

    and
    elements which appear as direct children under the element (and not nested at an arbitrary depth). This makes the whole problem much easier.

    Here is one way to accomplish it: To get the contents of the first part, you could use a template which will process a set of sibling nodes until the maximum string length is exceeded and a br or p is encountered, and then stop.

      
        
        
          
          
            
          
        
      
    

    And for the second part, you could create another template which searches for the same condition as the previous template, but outputs nothing until after that point:

      
        
        
          
            
              
            
          
          
             
              
            
            
          
        
      
    

    And here's how you can use those templates to split a story into two

    s.

      
        
          
          

提交回复
热议问题