XSLT:匹配N级节点

时间:2013-04-05 15:49:58

标签: xml recursion xslt-1.0

需要按ID匹配节点。 (比如a2-2)

XML:

<node id="a" title="Title a">
  <node id="a1" title="Title a1" />
  <node id="a2" title="Title a2" >
    <node id="a2-1" title="Title a2-1" />
    <node id="a2-2" title="Title a2-2" />
    <node id="a2-3" title="Title a2-3" />
  </node>
  <node id="a3" title="Title a3" />
</node>
<node id="b">
  <node id="b1" title="Title b1" />
</node>

当前解决方案:

<xsl:apply-templates select="node" mode="all">
  <xsl:with-param name="id" select="'a2-2'" />
</xsl:apply-templates>

 <xsl:template match="node" mode="all">
    <xsl:param name="id" />
    <xsl:choose>
      <xsl:when test="@id=$id">
        <xsl:apply-templates mode="match" select="." />
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates mode="all" select="node">
          <xsl:with-param name="id" select="$id" />
        </xsl:apply-templates>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="node" mode="match">
    <h3><xsl:value-of select="@title"/>.</h3>
  </xsl:template>

问题:
对于一个相当普遍的问题,上述解决方案似乎非常笨重 我过于复杂吗?有没有更简单的解决方案。

1 个答案:

答案 0 :(得分:1)

此解决方案缩短了两倍且更简单(单个模板且无模式)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <xsl:param name="pId" select="'a2-2'"/>

 <xsl:template match="node">
  <xsl:choose>
   <xsl:when test="@id = $pId">
    <h3><xsl:value-of select="@title"/>.</h3>
   </xsl:when>
   <xsl:otherwise><xsl:apply-templates/></xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>