methuselah
methuselah

Reputation: 13206

XPath expression to select node if it matches a specific attribute value

I am trying to find the minimum and maximum id values in r:waypoints/r:waypoint.

i.e. in this case: r:waypoint id="1" would be the minimum and r:waypoint id="3" would be the maximum.

Once found, I want to select the value in <a:place></a:place>, but if <a:place></a:place> is not available, I want to select the value in <a:street></a:street>. Is it not possible?

XSL

My attempt at finding the minimum, this returns everything in the node however, and not <a:place></a:place> as intended.

<xsl:for-each select="r:rides/r:ride">
     <xsl:value-of select="//*[contains(r:waypoints/r:waypoint/@id,'1')]"/>
</xsl:for-each>

XML

<r:rides>
    <r:ride>
        <r:lead pickup="1" dropoff="2">
        </r:lead>
        <r:passenger pickup="1" dropoff="3">
        </r:passenger>
        <r:waypoints>
            <r:waypoint id="1">
                <a:place>Victory Hall</a:place>     
                <a:street></a:street>       
            </r:waypoint>
            <r:waypoint id="2">
                <a:street></a:street>           
            </r:waypoint>
            <r:waypoint id="3">
                <a:street>Harbridge Avenue</a:street>       
            </r:waypoint>
        </r:waypoints>
    </r:ride>
</r:rides>

Expected Output

Victory Hall to Harbridge Avenue

Upvotes: 0

Views: 272

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

Try something like:

<xsl:template match="ride">
    <xsl:for-each select="waypoints/waypoint">
        <xsl:sort select="@id" data-type="number" order="ascending"/>
        <xsl:if test="position()=1">
            <xsl:value-of select="(place|street)[1]" />
            <xsl:text> to </xsl:text>
        </xsl:if>
        <xsl:if test="position()=last()">
            <xsl:value-of select="(place|street)[1]" />
        </xsl:if>
    </xsl:for-each>
</xsl:template>

Note: I have removed the prefixes because they are not bound to a namespace.

Upvotes: 1

Related Questions