2009-10-03 55 views
1

我已經創建了XSLT但我還想能夠對數據進行排序,還可以添加某種指數的,所以我可以組項目一起,難度林有就是我想要的節點排序依據包含多個值 - 值id喜歡排序。XSLT - 排序多個值

例如,下面是我的XML:

<item> 
<title>Item 1</title> 
<subjects>English,Maths,Science,</subjects> 
<description>Blah Blah Bah...</description> 
</item> 
<item> 
<title>Item 2</title> 
<subjects>Geography,Physical Education</subjects> 
<description>Blah Blah Bah...</description> 
</item> 
<item> 
<title>Item 3</title> 
<subjects>History, Technology</subjects> 
<description>Blah Blah Bah...</description> 
</item> 
<item> 
<title>Item 4</title> 
<subjects>Maths</subjects> 
<description>Blah Blah Bah...</description> 
</item> 

所以,如果我排序<subjects>我得到這樣的順序:

English,Maths,Science, 
Geography,Physical Education 
History, Technology 
Maths 

不過,我想這樣的輸出:

English 
Geography 
History 
Maths 
Maths 
Physical Education 
Science 
Technology 

輸出<subjects>中包含的每個主題的XML,因此Item1包含主題數學,英語&科學,所以我想輸出標題和描述3次,因爲它與所有3個科目有關。

什麼在XSLT的最好辦法做到這一點?

+0

XSLT 1.0或2.0? – 2009-10-04 00:07:48

+0

這是XSLT 1.0 – CLiown 2009-10-04 10:43:09

回答

1

我認爲這樣做是通過使用節點集extenstion函數來完成多通道處理的一種方式。首先,你將遍歷現有的主題節點,用逗號分割它們,以創建一組新的節點;每個主題一個。

接下來,您將通過在受順序設置這個新的節點循環。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="urn:schemas-microsoft-com:xslt" extension-element-prefixes="exsl" version="1.0"> 

    <xsl:output method="text"/> 

    <xsl:template match="/"> 
     <xsl:variable name="newitems"> 
     <xsl:for-each select="items/item"> 
      <xsl:call-template name="splititems"> 
       <xsl:with-param name="itemtext" select="subjects"/> 
      </xsl:call-template> 
     </xsl:for-each> 
     </xsl:variable> 
     <xsl:for-each select="exsl:node-set($newitems)/item"> 
     <xsl:sort select="text()"/> 
     <xsl:value-of select="text()"/> 
     <xsl:text> </xsl:text> 
     </xsl:for-each> 
    </xsl:template> 

    <xsl:template name="splititems"> 
     <xsl:param name="itemtext"/> 
     <xsl:choose> 
     <xsl:when test="contains($itemtext, ',')"> 
      <item> 
       <xsl:value-of select="substring-before($itemtext, ',')"/> 
      </item> 
      <xsl:call-template name="splititems"> 
       <xsl:with-param name="itemtext" select="substring-after($itemtext, ',')"/> 
      </xsl:call-template> 
     </xsl:when> 
     <xsl:when test="string-length($itemtext) &gt; 0"> 
      <item> 
       <xsl:value-of select="$itemtext"/> 
      </item> 
     </xsl:when> 
     </xsl:choose> 
    </xsl:template> 

</xsl:stylesheet> 

請注意,上述示例使用Microsoft的擴展功能。根據您使用的XSLT處理器的不同,您可能必須爲處理器指定其他名稱空間。

您可能還需要科目做一些「微調」,因爲你的XML樣本中上面,沒有在逗號分隔列表中的對象(技術)的一個前一個空間。

1

好,處理文本節點的內容是不是真的XSLT的任務。如果可以的話,您可能應該更改表示形式以將更多XML結構添加到主題元素中。否則,您將不得不使用XPath字符串函數編寫一些非常聰明的字符串處理代碼,或者可能使用基於Java的XSLT處理器並將字符串處理交給Java方法。這並不簡單。