2013-04-05 89 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