XSLT drop-down tree

    Let's say we have something hierarchical on our site. For example, product categories. Categories have subcategories and so on. And let us want to display this hierarchy in the drop-down list.

    For example, our structure is expressed in the following XML:

      
        
          
            
              
                
              

              
                
              

            

          

          
            
              
                
              

              
                
              

            

          

        

      

      
        
          
            
              
                
              

              
                
              

            

          

          
            
              
                
              

              
                
              

            

          

        

      



    * This source code was highlighted with Source Code Highlighter.
    NB: Actually, storing strings in attributes is not good; they should be made as separate nodes and wrapped in CDATA. However, here the title is precisely an attribute in order to save space. So please do not take a bad example.
    So, we now need to form a drop-down list from this XML. The easiest way to do this is to write the following conversion:

      

      
        
      

      
      
        
      



    * This source code was highlighted with Source Code Highlighter.

    As a result, we get such a picture.
    Ugly list
    In general, it works, but I want the category tree to look like a tree. And, since we have here select, you can get this tree only by placing spaces in the right places. There are, of course, optgroups, but they will not save us in this case, because categories can have arbitrarily large nesting.

    Decision


    Here such a bike solves a given problem:

      

      
        
      


      
        
        
          
          
            
              
            

          

        

      



    * This source code was highlighted with Source Code Highlighter.

    As a result, we get the following:
    Beautiful tree

    Also popular now: