ptn77
ptn77

Reputation: 627

xslt: working with attribute values to retrieve another "same parent" element's attribute

I have the following xml, where there can be multiple Person and Location elements:

<ProtectionOrderResponse>
  <Person id="PRTPER1">
    <!--child elements-->
  </Person>
  <Location id="PRTADR1"> 
    <!--child elements-->
  </Location>
  <PersonLocationAssociation>
        <PersonReference ref="PRTPER1"/>
        <LocationReference ref="PRTADR1"/>
  </PersonLocationAssociation>
</ProtectionOrderResponse>

I need an xslt that iterates through each Person element to retrieve its id attribute and match it with the ref attribute of the PersonLocationAssociation/PersonReference. From there, I would like to obtain the attribute value "PRTADR1" and put it into a variable using xslt given the Person attribute value "PRTPER1". The following is the simplified version of the xslt that I'm working on:

<xsl:template match="//ProtectionOrderResponse">
  <!--Although I'm iterating through all the Person elements, I only want to select particular Person elements that match a specific criteria, not sure how to do this yet so I will put the logic in the template section-->
  <xsl:for-each select="//Person">
     <xsl:apply-templates select="."/>
  </xsl:for-each>
</xsl:template>

<xsl:template match="Person">
<!--Logic to only process the Person element that matches a particular criteria and get the LocationReference for that Person-->
<xsl:variable name="PerID" select="Person/@id"/>
  <!-- need to obtain the ref attribute value of PersonLocationAssociation/LocationReference for the PersonLocationAssociation/PersonReference[@ref=$PerID]-->
</xsl:template>

What I need is to obtain the ref attribute value of PersonLocationAssociation/LocationReference for the PersonLocationAssociation/PersonReference[@ref=$PerID]. How would I do this? thanks!

Upvotes: 0

Views: 829

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Use keys:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:key name="ref-per" match="ProtectionOrderResponse/Person" use="@id"/>

    <xsl:key name="ref-loc" match="PersonLocationAssociation/LocationReference" use="../PersonReference/@ref"/>

    <xsl:template match="ProtectionOrderResponse">
        <xsl:apply-templates select="key('ref-per', 'PRTPER1')"/>
    </xsl:template>

    <xsl:template match="Person">
        <xsl:variable name="ref" select="key('ref-loc', @id)/@ref"/>
        <xsl:value-of select="$ref"/>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Related Questions