tags:

views:

45

answers:

1
+2  Q: 

Basic XSLT example

I'm just getting started using XSL to transform XML to HTML and I'm hopping to get help with the following to help me dive in.

Given XML like the following (A):

<Course Title="SampleCourse">
  <Lesson Title="Overview"/>
  <Section Title="Section1">
    <Lesson Title="S1 Lesson 1" />
    <Lesson Title="S1 Lesson 2" />
  </Section>
  <Section Title="Sections 2">
    <Lesson Title="S2 Lesson 1" />
  </Section>
</Course>

Or like (B):

<Course Title="SampleCourse">
  <Section Title="Section1">
    <Lesson Title="S1 Lesson 1" />
    <Lesson Title="S1 Lesson 2" />
  </Section>
  <Section Title="Sections 2">
    <Lesson Title="S2 Lesson 1" />
  </Section>
</Course>

How would I produce an XSL file that could transform the above examples to (A):

<h3>SampleCourse</h3>
<ul>
  <li>Overview</li>
  <li>Section1</li>
  <ul>
    <li>S1 Lesson 1</li>
    <li>S1 Lesson 2</li>
  </ul>
  <li>Sections 2</li>
  <ul>
    <li>S1 Lesson 1</li>
  </ul>
</ul>

or (B):

<h3>SampleCourse</h3>
<ul>
  <li>Section1</li>
  <ul>
    <li>S1 Lesson 1</li>
    <li>S1 Lesson 2</li>
  </ul>
  <li>Sections 2</li>
  <ul>
    <li>S1 Lesson 1</li>
  </ul>
</ul>

Thanks!

+3  A: 
<xsl:template match="Course"> <!-- We use template to define what shows up when we encounter the element "Course" -->
    <h3><xsl:value-of select="@Title"/></h3> <!-- value-of is used here to grab the title. @ is for attribute. -->
    <ul>
        <xsl:apply-templates/> <!-- apply-templates continues parsing down the tree, looking for more template matches. -->
    </ul>
</xsl:template>

<xsl:template match="Section">
    <li><xsl:value-of select="@Title"/></li>
    <ul>
        <xsl:apply-templates/>
    </ul>
</xsl:template>

<xsl:template match="Lesson">
    <li><xsl:value-of select="@Title"/></li>
</xsl:template>
andyvn22
Thanks, that made it very clear for me, much appreciated! (One small note to any cut n pasters like myself, @title should be @Title with the above example)
Evan
Whoops, yes; edited. :)
andyvn22
@andyvn22: +1 Good answer!
Alejandro