2015-04-26 35 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