2010-07-28 60 views
0

我有一個使用XML + XSLT編碼的網站,它爲我提供了一個完整的HTML網站。現在,爲了使網站更加美觀,我想分割文檔的一些部分:頁眉,頁腳和側邊欄。我在看谷歌,我發現這個解決方案:在XSLT中包含一個XML,然後應用一個foreach

<xsl:param name="doc" select="document('menu.xml')"/> 
<xsl:template match="/"> 
<html><head></head><body><xsl:for-each 
select="$doc"><xsl:apply-templates/></xsl:for-each></body></html> 
</xsl:template> 

我試圖申請它,我可以得到它的工作。這是我使用的方式:

由於xsl位於文件夾內,因此我將路由更改爲「../menu.xml」,這很有效。

<?xml version="1.0" encoding="ISO-8859-1"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:param name="menu" select="document('../menu.xml')"/> 

    <xsl:template match="/"> 

更有效,工作代碼,然後:

<ul class="menu_top"> 
    <xsl:for-each select="$menu"> 
     <li> 
      <a> 
       <xsl:attribute name="href"> 
        #<xsl:value-of select="link" /> 
       </xsl:attribute> 

       <xsl:value-of select="name"/> 
      </a> 
     </li> 
    </xsl:for-each> 
</ul> 
<xsl:for-each select="$menu"> 
    <div class="submenu"> 
     <xsl:attribute name="id"> 
      <xsl:value-of select="link" /> 
     </xsl:attribute> 

     <ul> 
      <xsl:for-each select="child"> 
       <li> 
        <a> 
         <xsl:attribute name="href"> 
          <xsl:value-of select="link" /> 
         </xsl:attribute> 

         <xsl:value-of select="name"/> 
        </a> 
       </li> 
      </xsl:for-each> 
     </ul> 
    </div> 
</xsl:for-each> 

最後我menu.xml文件:

<?xml version="1.0" encoding="utf-8"?> 
    <menu> 
     <category> 
      <name>First</name> 
      <link>menu-1</link> 

      <child> 
       <name>Child 1</name> 
       <link>#</link> 
      </child> 

      <child> 
       <name>Child 2</name> 
       <link>#</link> 
      </child>   
     </category> 
</menu> 

我有多個類別條目,但我簡化它。

提前致謝!

回答

2

document()函數返回要導入的文件的根目錄。在這種情況下,這是menu元素,而不是category元素。如果您想循環訪問類別,請使用以下代碼:

<xsl:for-each select="$menu/menu/category"> 
    ... 
+0

謝謝Welbog!這工作正常。我試圖投票,但我沒有足夠的聲譽!再次感謝! :) – ipalaus 2010-07-28 12:09:56

+0

@Isern Palaus:另外,沒有必要爲所有'for-each'。它是完全有效的'apply-templates select =「$ doc」'。檢查我的XML/XSLT客戶端網站http://www.aranedabienesraices.com.ar – 2010-07-28 13:18:56

+0

@Alejando我不知道如何使用正確的模板。 :( – ipalaus 2010-07-28 14:07:50

相關問題