RE: [xsl] XSL to create nested list items?

Subject: RE: [xsl] XSL to create nested list items?
From: <Jarno.Elovirta@xxxxxxxxx>
Date: Fri, 19 Nov 2004 11:59:23 +0200
Hi,

> I'm new to the list, and a relative newbie to XSL.  I'm able
> to do the simpler
> things, but am still learning.
>
> At the moment, I'm having problems figuring out how to store
> menu items in
> XML, then render them in XSL.
>
> I'm trying to get output something like this:
>
> <ul>
>   <li>
> 	One
> 	<ul>
> 		<li>One dot One</li>
> 	</ul>
>   </li>
> </ul>
>
> Of course, there can be multiple top level items, each of
> which may have many
> sub items and/or sub-lists.
>
> With regards to the XML, I've tried to create a nested
> structure something
> like so:
>
> <menu>
>   <item>
> 	<name>One</name>
> 	<url></url>
> 	<item>
> 		<name>One dot One</name>
> 		<url>http://someplace.com</url>
> 	</item>
>   </item>
> </menu>

Look good, models the hierarchy using hierarchy, easy to write a conversion
for.

> I like this structure as it directly reflects the menu, but
> have only had some
> success with the XSL.  I could not get the sub menu items to
> be treated
> differently - the only way I could make this work was to
> enclose each <li>
> item in <ul>, and that's not quite what I want.

  <xsl:template match="menu">
    <html>
      <head>
        <title></title>
      </head>
      <body>
        <ul>
          <xsl:apply-templates select="item"/>
        </ul>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="item">
    <li>
      <a href="{url}">
        <xsl:value-of select="name"/>
      </a>
      <xsl:if test="item">
        <ul>
          <xsl:apply-templates select="item"/>
        </ul>
      </xsl:if>
    </li>
  </xsl:template>

> So I tried to change the XML a bit to something like so:
>
> <menu>
> 	<item parent="0">
> 		<id>1</id>
> 		<name>One</name>
> 		<url></url>
> 	</item>
> 	<item parent="1">
> 		<id>2</id>
> 		<name>One dot One</name>
> 		<url>http://someplace.com</url>
> 	</item>
> </menu>
>
> I have partial success with this method as well, but cannot
> properly select
> the parent items only (any item with a parent=0), and then
> create the correct
> sub list.

But if you have multiple top-level items, do they all have @parent = 0? How do
you know which item is inside which. I think you're better off using the
earlier XML vocabulary. If you want to add numbering, add

  <xsl:number level="multiple"/>

as the first child of li element, just before a element.

Cheers,

Jarno

Current Thread