基本的XSLT示例

时间:2010-08-15 22:47:42

标签: xml xslt

我刚刚开始使用XSL将XML转换为HTML,我正在寻求帮助以帮助我深入了解。

给定XML如下(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>

或者喜欢(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>

如何生成可将上述示例转换为(A)的XSL文件:

<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>

或(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>

谢谢!

1 个答案:

答案 0 :(得分:5)

<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>