2009-05-22 58 views
10

我的要求是 - 使用XSLT-來顯示美國各州的下拉列表,並且打印'選定'在XML中聲明的特定使用我的樣式表。如何在XSLT中聲明和迭代數組?

我在想用狀態聲明一個數組並重復它,但我不知道該怎麼做。

注:更多的想法,歡迎;)

回答

12

的一種方式做,這是對國家數據嵌入到樣式表本身,並訪問使用document('')樣式表文件,內容如下:

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:my="whatever" 
    exclude-result-prefixes="my"> 

    <xsl:output indent="yes"/> 

    <!-- The value of the state you want to select, supplied in the input XML --> 
    <xsl:variable name="selected-state" select="/xpath/to/state/value"/> 

    <!-- You have to use a namespace, or the XSLT processor will complain --> 
    <my:states> 
    <option>Alabama</option> 
    <option>Alaska</option> 
    <!-- ... --> 
    <option>Wisconsin</option> 
    <option>Wyoming</option> 
    </my:states> 

    <xsl:template match="/"> 
    <!-- rest of HTML --> 
    <select name="state"> 
     <!-- Access the embedded document as an internal "config" file --> 
     <xsl:apply-templates select="document('')/*/my:states/option"/> 
    </select> 
    <!-- rest of HTML --> 
    </xsl:template> 

      <!-- Copy each option --> 
      <xsl:template match="option"> 
      <xsl:copy> 
       <!-- Add selected="selected" if this is the one --> 
       <xsl:if test=". = $selected-state"> 
       <xsl:attribute name="selected">selected</xsl:attribute> 
       </xsl:if> 
       <xsl:value-of select="."/> 
      </xsl:copy> 
      </xsl:template> 

</xsl:stylesheet> 

讓我知道如果您有任何問題。

1

理想情況下,你會狀態列表存儲在XML文件中,只使用XSLT來遍歷他們。

更新: 如果您不能編輯XML,你可以看看使用document function從第二個數據文件加載數據:

+0

我無法更改XML,它由另一個系統提供 – 2009-05-22 22:35:05

+0

您仍然可以使用文檔功能訪問另一個包含狀態列表的靜態XML文檔,對吧? – Elijah 2009-05-23 00:20:45