2011-10-25 582 views
1

我有一個for-each我想按某個值排序。但我循環的東西只有一個允許連接到值的鍵。謂詞中循環中當前元素的訪問屬性

<xsl:for-each select="/foo/keys/key"> 
    <xsl:sort select="/foo/things/thing[@[email protected]]"/> 
    <xsl:value-of select="@id"/> 
</xsl:for-each> 

這似乎並不工作:爲一個文件一個簡單的例子:

<foo> 
    <keys> 
    <key id="foo"/> 
    <key id="bar"/> 
    </keys> 

    <things> 
    <thing name="foo"><desc>some description</desc></thing> 
    <thing name="bar"><desc>another description</desc></thing> 
    </things> 
</foo> 

和樣式表。 @id涉及來自環路的key元素; @name與謂詞thing有關。我該如何解決這個問題?我試着分配/foo/keys/key/@id給一個變量和使用,但<sort>必須在換每個...

回答

1

使用current()函數的第一個元素:

<xsl:sort select="/foo/things/thing[@name = current()/@id]"/> 

參考:http://www.w3.org/TR/xslt#misc-func

XML:

<foo> 
    <keys> 
     <key id="1"/> 
     <key id="2"/> 
     <key id="3"/> 
     <key id="4"/> 
    </keys> 

    <things> 
     <thing name="2"> 
      <desc>a</desc> 
     </thing> 
     <thing name="4"> 
      <desc>b</desc> 
     </thing> 
     <thing name="3"> 
      <desc>c</desc> 
     </thing> 
     <thing name="1"> 
      <desc>d</desc> 
     </thing> 
    </things> 
</foo> 

XSLT:

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


    <xsl:template match="/"> 
     <xsl:for-each select="/foo/keys/key"> 
      <xsl:sort select="/foo/things/thing[@name = current()/@id]"/> 
      <xsl:value-of select="@id"/> 
     </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 

輸出:

2431 
+0

感謝。它不能解決我的問題,但這不是你的錯。在我的真實樣式表中,「keys」和「things」存在於不同的文檔中(關鍵字通過document()包含在內),並且我不能同時訪問它們。我想我會接受你的答案。 – musiKk