2016-01-11 39 views
0
<handlingInstruction> 
    <handlingInstructionText>CTAC | MARTINE HOEYLAERTS</handlingInstructionText> 
</handlingInstruction> 
<handlingInstruction> 
    <handlingInstructionText>PHON | 02/7225235</handlingInstructionText> 
</handlingInstruction> 

我上面給出的XML結構我將它們連接起來,並使用下面的代碼使用逗號作爲分隔符顯示分隔一次只有2個值存在

> <xsl:value-of 
> select="concat(handlingInstruction[1]/handlingInstructionText, 
>        ',', 
>        handlingInstruction[2]/handlingInstructionText)"/> 

我想問一下我如何使逗號分隔符只有在第二次存在時才能以最短的方式出現。在此先感謝

+0

會不會有永遠是1個或2 handlingInstruction節點?可能會有3個或更多,如果是,還是隻有第一個2,你會不會處理所有的問題? – Matthew

回答

1

如果你不想使用xsl:for-each,嘗試:(從這裏繼續說道:https://stackoverflow.com/a/34679465/3016153

<xsl:template match="/root"> 
    <xsl:apply-templates select="handlingInstruction/handlingInstructionText"/> 
</xsl:template> 

<xsl:template match="handlingInstructionText"> 
    <xsl:value-of select="."/> 
    <xsl:if test="position()!=last()"> 
     <xsl:text>,</xsl:text> 
    </xsl:if> 
</xsl:template> 

+0

謝謝它適用於我。 –

1
<xsl:for-each select="handlingInstruction"> 
    <xsl:value-of select="handlingInstructionText"/> 
    <xsl:if test="position()!=last()"> 
     <xsl:text>,</xsl:text> 
    </xsl:if> 
</xsl:for-each> 

這將迭代所有handlingInstruction元素並輸出handlingInstructionText元素的值。它會添加到每個元素的末尾,如果它不是最後一個元素(第一個元素只有一個元素),則爲逗號。

在您的示例中,您只使用了兩個handlingInstruction元素。如果只想用這兩種方法,請執行

<xsl:for-each select="handlingInstruction[position()&lt;3]"> 
    <xsl:value-of select="handlingInstructionText"/> 
    <xsl:if test="position()!=last()"> 
     <xsl:text>,</xsl:text> 
    </xsl:if> 
</xsl:for-each> 

請注意&lt;那裏。這實際上是一個小於號(<),但我們不能在xml中使用它,所以我們使用爲它定義的實體。

+0

感謝您的及時響應,但我試圖避免使用for-each –

+0

我添加了第二種方法,避免了for-each使用xslt2作爲附加答案。 – Matthew

0

這是第二種方法,它避免了for-each循環。

如果使用XSLT版本2,有一個字符串聯接功能可能等中使用:

<xsl:value-of select="string-join(//handlingInstruction/handlingInstructionText,',')"/> 

字符串聯接方法需要字符串序列(其選擇的節點將被轉換通過採取他們的內容)並連接他們與分隔符。如果只有一個字符串,則不會添加分隔符。

或者,xslt 2還會在value-of元素上提供分隔符屬性。因此,

<xsl:value-of select="//handlingInstruction/handlingInstructionText" separator=","/> 

產生相同的結果。

+0

我在這裏添加第二個答案,因爲它是從第一個答案中區分出來的方法,它是對問題有效的合法方法。 [This](http://meta.stackexchange.com/questions/60445/is-it-ok-to-post-multiple-answers-to-a-question)and [this](http://meta.stackexchange問題/問題/ 25209/What-is-the-official-etiquette-on-answering-a-question-twice)表明最好將這些作爲兩個單獨的答案。 – Matthew

+0

再次感謝string-join實際上是我在網上看到的功能之一,但令人遺憾的是,這個功能不受我所擁有的xsl版本的支持。 –

+0

如果你不能使用xlst 2,我認爲for-each循環(或等價的)方法是唯一的可能。添加到xslt2的大部分功能都是爲了解決xslt 1中過度複雜的問題,就像這個問題一樣。 – Matthew