methuselah
methuselah

Reputation: 13216

Access node based on attribute value

Within my XML document, each lead or passenger has a pickup and dropoff attribute, which has a matching 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>

How would I select the a:place for each lead or passenger in the XSL? For example:

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

Expected outcome:

Route: Hall → Apartments

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

Expected outcome:

Route: Hall → Train Station

Upvotes: 0

Views: 50

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

To follow cross-references you can define and use a key, define the key with

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

then you can use e.g.

<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>

As the ids don't seem to be unique in your complete document more code is needed, in XSLT 2.0 you could use <xsl:value-of select="key('by-id', @pickup, ancestor::r:ride)"/>.

With XSLT 1.0 change the key definition to

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

and then the key uses to e.g. key('by-id', concat(generate-id(ancestor::r:ride), '|', @pickup)) and so on.

Upvotes: 1

Related Questions