2016-03-02 31 views
-1

考慮這個遞歸XSLT模板:的xsl:for-each循環意外的結果在條件測試

<xsl:template name="SUBREPORT_FIELDS" > 
    <xsl:for-each select="current()/section/@name"> 
    <xsl:choose> 
     <xsl:when test="current()/section/@name = $pSectionName"> 
     <xsl:call-template name="FieldSezione"/> 
     <xsl:call-template name="FIELDS"/> 
     </xsl:when> 
     <xsl:otherwise> 
     <xsl:call-template name="SUBREPORT_FIELDS"/> 
     </xsl:otherwise> 
    </xsl:choose> 
    </xsl:for-each> 
</xsl:template> 

而下面的XML輸入文件:

<box name="box3"> 
    <section name="sEmicrania"> 
    <box name="box4"> 
     <treecombobox name="tc"/> 
     <textmemo name ="tm"/> 
    </box> 
    <box name="box4"> 
     <section name="sZona"> 
     <box name="box5"> 
      <label name="label1"/> 
      <textmemo name="tmZona"/> 
     </box> 
     </section> 
    </box> 
    </section> 
</box> 

變量$ pSectionName將作爲其值「sEmicrania」或「sZona」;這些是兩個「<節>」元素的屬性「名稱」的值。

當變量$ pSectionName的值爲sEmicrania時,模板正確地將條件測試評估爲true,但如果變量的值爲「sZona」,則測試評估爲false。

我希望測試在兩種情況下均返回true。

+1

請發表** **重複性的例子 - 請參見:[MCVE] –

+0

我認爲你需要改變'current()/ section/@ name = $ pSectionName'就是'section/@ name = $ pSectionName'。 'current()'與'.'不同,儘管在大多數地方它們的行爲方式都是一樣的 – Pawel

+0

「傳遞變量」是什麼意思?您的模板未設置爲接受參數。 – Matthew

回答

0

我想你的模板,因爲它目前爲不會輸出任何東西,甚至在pSectionName的情況下被設置爲「sEmicrania」

你可以通過這樣開始:

<xsl:for-each select="current()/section/@name"> 

但如果你的當前節點是box元素,這將只會選擇任何東西。如果是這種情況,那麼在xsl:for-each構造中,上下文將是name屬性。但後來你有你的測試...

<xsl:when test="current()/section/@name = $pSectionName"> 
在這種情況下

current()name屬性,你定位在。這沒有一個叫section的孩子,所以這個測試是錯誤的。

而是調用xsl:otherwise以遞歸調用模板。這不會更改上下文,因此您仍然位於name屬性上。因此,此時xsl:for-each將不會選擇任何內容,因此沒有任何內容會被輸出。

我不完全確定你想達到什麼,但我不認爲你一定需要遞歸模板。如果你只是想選擇一個匹配名稱的section元素,你可以做這樣的事情

<xsl:template match="box"> 
    <xsl:apply-templates select=".//section[@name = $pSectionName]" /> 
</xsl:template> 

<xsl:template match="section"> 
    <!-- Do what you need to do here --> 
</xsl:template>