2011-07-23 44 views
3

我試圖使用XSLT顯示大學課程時間表。我DTS看起來是這樣的:使用XSLT顯示時間表

<?xml version="1.0" encoding="UTF-8"?> 
<!ELEMENT timetable (day,day,day,day,day,day,day)> 
<!ELEMENT day (session)*> 
<!ELEMENT session (begin,end,(course?))> 
<!ELEMENT course (#PCDATA)> 
<!ELEMENT begin (#PCDATA)> 
<!ELEMENT end (#PCDATA)> 

我想顯示在天/小時表看起來像這樣所有的課程(原諒可怕的設計):

timetable

麻煩的是,我想要做一個for each子句,但只是在常規數字上,而不是在xml的某些部分。這對XSLT來說可能嗎?例如,它可能會是這個樣子:

/* for each time = 8..17, do: */ 
    <xsl:for-each select="timetable/day"> 
     <xsl:value-of select="session[[begin&lt;/*time*/ or begin=/*time*/]/course" /> 
    </xsl:for-each> 

回答

2

您可以使用遞歸

<xsl:template name="for_i_from_8_to_17"> 
    <xsl:param name="i">8</xsl:param> <!-- initial value --> 
    <!-- do what you have to do --> 
    <xsl:if test="not($i = 17)"> 
     <xsl:call-template name="for_i_from_8_to_17"> 
      <xsl:with-param name="i"> 
     <xsl:value-of select="$i + 1"> 
     </xsl:with-param> 
     </xsl:call-template> 
    </xsl:if> 
</xsl:template> 

(從[email protected]稍微適應)

0

您可以使用遞歸:

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

    <xsl:template match="/"> 
    <html> 

     <head> 
     <style type="text/css">td{border:solid 1px black} table{border-collapse:collapse}</style> 
     </head> 

     <table> 
     <xsl:call-template name="for"> 
      <xsl:with-param name="count" select="10"/> 
     </xsl:call-template> 
     </table> 
    </html> 
    </xsl:template> 

    <xsl:template name="for"> 
    <xsl:param name="i" select="0"/> 
    <xsl:param name="count"/> 

    <xsl:if test="$i &lt; $count"> 
     <tr> 
     <td> 
      <xsl:value-of select="concat($i + 8, ':00 - ', $i + 9, ':00')"/> 
     </td> 
     </tr> 

     <xsl:call-template name="for"> 
     <xsl:with-param name="i" select="$i + 1"/> 
     <xsl:with-param name="count" select="$count"/> 
     </xsl:call-template> 
    </xsl:if> 

    </xsl:template> 

</xsl:stylesheet> 

輸出:

enter image description here

0

您將需要爲每個循環2。一個重複一週的幾天,一個重複一天中的幾個小時。 一天的時間可以用XSLT 2.0來解決容易這樣的:

<xsl:for-each select="8 to 17"> 
    <!-- do your stuff --> 
    <xsl:value-of select="." /> <!-- dot represents a number from the range --> 
</xsl:fo-each> 

的序列和範圍的全覆蓋見this

+0

我不太明白如何訪問迭代變量。你能證明嗎? –

+0

問題是表格和數據的渲染不相交。假設您無法填充表中的每個單元格都必須構建整個表格,然後使用日期和時間從XML文件中查找數據。 –

2
在XSLT 2.0

<xsl:variable name="timetable" select="timetable"> 
<table> 
    <thead> 
    .. output the table heading .. 
    </thead> 
    <tbody> 
    <xsl:for-each select="8 to 17"> 
    <tr> 
     <xsl:variable name="hour" select="."/> 
     <td><xsl:value-of select="$hour, '-', $hour+1"/></td>   
     <xsl:for-each select="$timetable/day"> 
     <td><xsl:value-of 
      select="session[begin lt $hour+1 and end gt $hour]/course"/> 
     </td> 
     </xsl:for-each> 
    </xsl:for-each> 
    </tbody> 
</table> 

再加上格式化一些工作。

+0

Eclipse抱怨'select =「8至17」'不是有效的xpath。什麼是正確的語法? –