XSLT:Transforming a flat list in a nested one

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vv1984
    New Member
    • Jul 2008
    • 1

    XSLT:Transforming a flat list in a nested one

    Hi to every one,
    I need some help with this simple (actually not so simple for me..) tranformation.
    I've got something like this:

    Code:
    <ul>
    <li class="chapter">Chapter1</li>
    <li class="sub">subchap1.1</li>
    <li class="sub">subchap1.2</li>
    <li class="chapter">Chapter2</li>
    <li class="sub">subchap2.1</li>
    <li class="sub">subchap2.2</li>
    </ul>
    ...and I'd like to obtain this:

    Code:
    <select>
    <optgroup label="Chapter1">
    <option>subchap1.1</option>
    <option>subchap1.2</option>
    </optgroup>
    <optgroup label="Chapter2">
    <option>subchap2.1</option>
    <option>subchap2.2</option>
    </optgroup>
    </select>
    I've tried this, but does not work properly, optgroup's just
    at option's same level:

    Code:
    <xsl:template match="ul">
    <select>
    <xsl:for-each select="li[@class='chapter']"> 
    	
    			<optgroup>
    				<xsl:attribute name="label">
    				<xsl:value-of select="current()"/>
    				</xsl:attribute>
    				
    				<xsl:for-each select="li[@class='sub']">
    			
    					<option>
    						<xsl:attribute name="value">
    							<xsl:value-of select="current()"/>
    						</xsl:attribute>
    						<xsl:value-of select="current()"/>
    					</option>	
    				
    				</xsl:for-each>	
    			</optgroup>
    	
    	</xsl:for-each>
    </select>
    </xsl:template>
    
    
    </xsl:stylesheet>
    Any suggest is welcome!!
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    I think it's like:
    [code=xml]
    <xsl:for-each select="followi ng-sibling::li[@class='sub'][generate-id(preceding-sibling::li[@class='chapter '][1]) = generate-id(current())]">
    [/code]

    Or you could use a key; that would require 2 lines of edits, but would be a little faster with larger files.

    Comment

    Working...