XSLT - how to parse xml with recursive elements to Eclipse toc.xml?

房东的猫 提交于 2019-12-09 04:24:26

I think the following does what you want:

<xsl:template match="BODY">
    <toc label="Sample Table of Contents">
        <xsl:apply-templates select="UL/LI/OBJECT"/>
  </toc>
</xsl:template>

<xsl:template match="OBJECT">
  <topic label="{param[@name='Name']/@value}" href="{param[@name='Local']/@value}">
    <xsl:apply-templates select="following-sibling::UL/LI/OBJECT"/>
  </topic>
</xsl:template>

Your main problem is this line:

<xsl:apply-templates select="//LI"  />

This produces a list of all <LI> elements in the input, and thus creates a flat output list. You can use the built-in recursion and "move with the flow", like this:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />

  <xsl:template match="BODY">
    <toc>
      <xsl:apply-templates select="OBJECT" />
      <xsl:apply-templates select="UL" />
    </toc>
  </xsl:template>

  <xsl:template match="UL">
    <xsl:apply-templates select="LI" />
  </xsl:template>

  <xsl:template match="LI">
    <topic>
      <xsl:apply-templates select="OBJECT" />
      <xsl:apply-templates select="UL" />
    </topic>
  </xsl:template>

  <xsl:template match="OBJECT">
    <xsl:apply-templates select="param" />
  </xsl:template>

  <xsl:template match="OBJECT/param">
    <xsl:variable name="attrName">
      <xsl:choose>
        <xsl:when test="@name = 'FrameName'">label</xsl:when>
        <xsl:when test="@name = 'Name'">label</xsl:when>
        <xsl:when test="@name = 'Local'">href</xsl:when>
      </xsl:choose>
    </xsl:variable>
    <xsl:if test="$attrName != ''">
      <xsl:attribute name="{$attrName}">
        <xsl:value-of select="@value" />
      </xsl:attribute>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

The output produced is:

<?xml version="1.0" encoding="utf-8"?>
<toc label="contents">
  <topic label="Title1" href="Ref1">
    <topic label="Title 2" href="Ref2">
      <topic label="Title3" href="Ref3"></topic>
      <topic label="Title4" href="Ref4"></topic>
    </topic>
    <topic label="Title5" href="Ref5"></topic>
  </topic>
  <topic label="Title6" href="Ref6"></topic>
</toc>

Note that I replaced your "mode" templates whith an <xsl:choose>. The rest is fairly obvious, I think.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!