How to select the grandparent of a node using xslt

前端 未结 2 1529
悲&欢浪女
悲&欢浪女 2021-02-04 15:56

I\'m in a situation where I can only test for the child node, but I have to apply tags to the grandparent of this child node.

I\'ve tried using:



        
2条回答
  •  -上瘾入骨i
    2021-02-04 16:19

    I'm in a situation where I can only test for the child node, but I have to apply tags to the grandparent of this child node.

    XSLT isn't procedural programming, so you have to think about things a little differently.

    If I understand correctly, you want to inject new tags (additional child elements or attributes?) into your XML, but you want to add it to an ancestor when you find a specific descendant. Your example code appears to try to target the grandparent once you come across the child. Unfortunately, this may be too late.

    You may need inject the new element/attribute when engine comes across the element you want to modify (the grandparent in your case), not when it comes across the child that matches the condition (or else you'll end up adding elements or attributes to the child)

    Consider this input (grandparent="album", grandchild="label"):

    
    
     
      Sgt. Pepper's Lonely Hearts Club Band  
      The Beatles  
      1967  
       
          
         
       
    
    

    I want to modify the album based on whether a certain label is present. Remember the general format for targeting nodes is: target-node[target-condition]. To modify any album elements that have a Capitol label grandchild element, I'd use this:

    album[*/label='Capitol']
    

    So consider this stylesheet to add a new attribute and 2 new child elements to album's that match my condition:

    
    
      
    
       
         
           
         
        
    
       
         
          
          A Capitol Record  
           
            
           
         
       
    
    
    

    Output (manually formatted):

    
     
       
      Sgt. Pepper's Lonely Hearts Club Band  
      The Beatles  
      1967  
       
          
         
       
      
    
    

    Some sandbox test resources:

    • http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
      • To see what nodes a given XPath expression actually targets
    • http://unindented.org/projects/xslt-tester-applet/run/
      • To try out a stylesheet

提交回复
热议问题