2010-12-02 129 views
2

嗨 我需要通過xsl獲取元素數組(前「 - 」如果存在)。xsl獲取元素數組

XML是

<Cars> 
<Car Trunck="511"/> 
<Car Trunck="483-20"/> 
<Car Trunck="745"/> 
</Cars> 

XSL是

<xsl:variable name="testarr"> 
<xsl:for-each select="//Cars//Car/@Trunck"> 
<xsl:value-of select="number(substring(.,1,3))" /> 
       </xsl:for-each> 
         </xsl:variable> 

(我假設所有的數字是三位數字,如果有人知道的所有情況的解決方案將高興地聽到提案) 如果我這樣做 我得到所有數字在一行:511483745 ,我需要讓他們在數組 ,因爲我也需要得到最大值

感謝

+0

XSLT沒有「數組」的概念 - 最接近的是節點集。 – Oded 2010-12-02 08:17:08

+0

好問題,+1。 @亞歷杭德羅的回答明顯好於當前選定的答案,我向其投了贊成票。不過,我認爲我的答案更好。 :) – 2010-12-03 05:23:39

回答

1

您可以使用substring-beforesubstring-after功能:看到優秀的ZVON教程 http://zvon.org/xxl/XSLTreference/Output/function_substring-after.html

在你的榜樣,你只提取其中獲得級聯值(這是字符串)。也許你需要包裝的結果在自己的元素

<xsl:for-each select="//Cars//Car/@Trunck"> 
    <truck> 
    <xsl:value-of select="number(substring(.,1,3))" /> 
    </truck> 
</xsl:for-each> 
2

您好我需要得到元素的數組 (之前「 - 」如果存在的話)[...]我需要得到 他們數組,因爲我還需要得到 最大值

這個樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/"> 
     <xsl:for-each select="/Cars/Car/@Trunck"> 
      <xsl:sort select="concat(substring-before(.,'-'), 
            substring(., 1 div not(contains(.,'-'))))" 
        data-type="number" order="descending"/> 
      <xsl:if test="position()=1"> 
       <xsl:value-of 
        select="concat(substring-before(.,'-'), 
            substring(.,1 div not(contains(.,'-'))))"/> 
      </xsl:if> 
     </xsl:for-each> 
    </xsl:template> 
</xsl:stylesheet> 

輸出:

745 

的XPath 2.0一行:

max(/Cars/Car/@Trunck/number(replace(.,'-.*',''))) 
+0

+1爲最佳解決方案。 – 2010-12-03 05:07:29

0

當你有兩個很好的答案(尤其是由@Alejandro),這裏有一個從我,我覺得是更好:

這改造

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="text"/> 
<xsl:param name="pTopNums" select="2"/> 

<xsl:template match="/*"> 
    <xsl:apply-templates select="*"> 
    <xsl:sort data-type="number" order="descending" 
    select="substring-before(concat(@Trunck,'-'),'-')"/> 
    </xsl:apply-templates> 
</xsl:template> 

<xsl:template match="Car"> 
    <xsl:if test="not(position() > $pTopNums)"> 
    <xsl:value-of select= 
    "substring-before(concat(@Trunck,'-'),'-')"/> 
    <xsl:text>&#xA;</xsl:text> 
    </xsl:if> 
</xsl:template> 
</xsl:stylesheet> 

當APPLI ED此XML文檔上(原始提供的一個,略微改變爲更具挑戰性):

<Cars> 
    <Car Trunck="483-20"/> 
    <Car Trunck="311"/> 
    <Car Trunck="745"/> 
</Cars> 

產生想要的,正確的結果(即從@Trunck導出在問題中指定的頂部的兩個數字):

745 
483