2013-12-23 51 views
0

嗨我是XSL的新手,我正在嘗試創建一個XSL樣式表,以便根據他們寫入的文章數量來打印最常見作者的名稱,如XML文檔中所指定的那樣。XSL最常見的

XML

<?xml version="1.0"?> 
<?xml-stylesheet type="text/xsl" href="busiestAuthor.xsl"?> 
<latestIssue> 
<issue number="357" /> 
<date> 
    <day> 4 </day> 
    <month> 1 </month> 
    <year> 2013 </year> 
</date> 

<stories> 
    <story> 
     <title> The earth is flat </title> 
     <author> Tom Friedman </author> 
     <url> http://www.HotStuff.ie/stories/story133456.xml </url> 
    </story> 

    <story> 
     <title> Films to watch out for in 2013 </title> 
     <author> Brated Film Critic </author> 
     <url> http://www.HotStuff.ie/stories/story133457.xml </url> 
    </story> 

    <story> 
     <title> The state of the economy </title> 
     <author> Tom Friedman </author> 
     <url> http://www.HotStuff.ie/stories/story133458.xml </url> 
    </story> 

    <story> 
     <title> Will an asteroid strike earth this year? </title> 
     <author> Stargazer </author> 
     <url> http://www.HotStuff.ie/stories/story133459.xml </url> 
    </story> 
</stories> 
</latestIssue> 

所以結果我想busiestAuthor.xsl打印只是弗裏德曼,因爲他寫了2篇文章和其他人只有寫一個。我相信這可能很容易,但正如我所說,我對這一切都很陌生,我似乎無法管理它。在每個循環和排序之間,我的頭在旋轉。

感謝大家,我正在大學讀書,這樣的一個問題會以某種形式或形式出現在我的期末考試中。乾杯!

+2

你可以用你試過的東西,你使用的處理器和你使用的是什麼版本的XSLT更新你的問題?否則,對於基本思想,您將希望查找針對XSLT 1.0的Muenchian方法和針對XSLT 2.0的for-each-group。 –

回答

2

這裏最有用的策略可能是

  1. 在比賽的人數的遞減順序定義關鍵給你所有的故事對於一個給定的作者姓名
  2. 排序作者列表它的鍵值
  3. 採取

關鍵定義去外面所有的模板,這個名單只是第一個元素:

<xsl:key name="storiesByAuthor" match="story" use="author" /> 

然後,通過故事的數量進行排序,並採取的第一個元素,你需要做這樣的事情在XSLT 1.0:

<xsl:for-each select="/latestIssue/stories/story/author"> 
    <xsl:sort select="count(key('storiesByAuthor', .))" 
      data-type="number" order="descending" /> 
    <xsl:if test="position() = 1"> 
    <!-- in here, . is one of the author elements for the author with the 
     most stories --> 
    </xsl:if> 
</xsl:for-each> 

,這對於-每個產生重複的事實這裏沒有問題,因爲你只關心第一個「迭代」。如果您有多個作者的最大故事數量相同,您會在原始文檔中獲得最先提及的作者(因爲xsl:sort是「穩定的」,即按文檔順序返回具有相同排序鍵值的項目)。

對於XSLT 2.0,你可以使用xsl:perform-sort代替for-each,但由於你使用<?xml-stylesheet?>我相信你正在做的改造在瀏覽器中,大多數(全部?)只瀏覽器的支持1.0。

+0

+1另外在XSLT 2.0中,OP可以使用'distinct-values()'。我認爲你是對的,但是('<?xml-stylesheet?>')。 –