2015-04-26 36 views
0

在我的XML文檔中,每個潛在客戶或乘客都有一個pickupdropoff屬性,該屬性具有匹配的waypoint id。基於屬性值的訪問節點

<r:rides> 
    <r:ride> 
     <r:lead pickup="1" dropoff="2"> 
     </r:lead> 
     <r:passengers> 
      <r:passenger pickup="1" dropoff="3"> 
      </r:passenger> 
     </r:passengers> 
     <r:waypoints> 
      <r:waypoint id="1"> 
       <a:place>Hall</a:place> 
      </r:waypoint> 
      <r:waypoint id="2"> 
       <a:place>Apartments</a:place>  
      </r:waypoint> 
      <r:waypoint id="3"> 
       <a:place>Train Station</a:place> 
      </r:waypoint> 
     </r:waypoints> 
    </r:ride> 
</r:rides> 

如何爲XSL中的每位潛在客戶或乘客選擇a:place?例如:

<xsl:for-each select="r:lead"> 
    Route: <pickup goes here/> &#8594; <dropoff goes here/>          
</xsl:for-each> 

預期成果:

路線:霍爾→公寓

<xsl:for-each select="r:passengers/r:passenger"> 
    Route: <pickup goes here/> &#8594; <dropoff goes here/>          
</xsl:for-each> 

預期成果:

路線:霍爾→火車站

+1

請勿將XML與未綁定的前綴一起發佈。刪除前綴或包含名稱空間聲明。 –

+0

你是什麼意思?你的意思是'xmlns:r =「http://www.rideshare.com/ride」' – methuselah

+1

是的,這就是我的意思。 –

回答

1

要跟隨交叉引用,你可以定義和使用的關鍵,定義與

<xsl:key name="by-id" match="r:waypoints/r:waypoint/a:place" use="../@id"/> 

的關鍵,那麼你可以使用例如

<xsl:for-each select="r:lead"> 
    Route: <xsl:value-of select="key('by-id', @pickup)"/> &#8594; <xsl:value-of select="key('by-id', @dropoff)"/>          
</xsl:for-each> 

由於id小號似乎並沒有成爲你的完整文檔中唯一需要更多的代碼,在XSLT 2.0中,您可以使用<xsl:value-of select="key('by-id', @pickup, ancestor::r:ride)"/>

隨着XSLT 1.0改變

<xsl:key name="by-id" match="r:waypoints/r:waypoint/a:place" use="concat(generate-id(ancestor::r:ride), '|', ../@id)"/> 

,然後將密鑰使用密鑰定義成例如key('by-id', concat(generate-id(ancestor::r:ride), '|', @pickup))等。

+0

謝謝馬丁。 'xsl:key'值會去哪裏?在「for-each」之外? – methuselah

+0

'xsl:key'是一個頂級元素,可以作爲'xsl:stylesheet'或'xsl:transform'的直接子元素。 –

+0

好的,我已經完成了這個工作,並且對於從xml文檔中拉出的第一個'r:ride'節點可以正常工作,但是我發現在任何其他附加的'r:ride'節點上,它總是返回到第一節點(即上面概述的節點)。有什麼理由呢?我在這裏創建了當前文檔的一個pastebin:http://pastebin.com/6sSFuc63 – methuselah