2013-04-05 88 views
1

需要通过id匹配节点。 (比如A2-2)XSLT:匹配N级节点

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

该解决方案是两次短,更简单的(单个模板和无模式)

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

予保持与模式的单独模板匹配节点保持样式表干净作为变换为匹配节点很大。谢谢。 – 2013-04-08 08:25:46

+0

@SergejPopov,不客气。 – 2013-04-08 14:28:06