leas
leas

Reputation: 379

how to match key with different values using a variable in xslt?

The general purpose of my code is to generate an html document displaying some of the infos in my xml document. I am trying to get the name of a doctor based on their id. Here's what my xml document looks like :

    <hospital>
        <doctors>
            <doctor>
                <name>john</name>
                <id>1</id>
                ...
            </doctor>
            <doctor>
                <name>steve</name>
                <id>2</id>
                ...
           </doctor>
        </doctors>
        <records>
           <record>
              <doctor id="1" />
              <date>...</date>
              <patient>
              ...
              </patient>
           </record>
        </records>
    </hospital>

this is my xslt code :

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="ids" match="doctor" use="id" />

      <xsl:template match="/">
        ...
        <xsl:apply-templates select="hospital/records/record"/>
        ...
      </xsl:template>

      <xsl:template match="record">
        ...
        Doctor identification : <xsl:value-of select="doctor/@id" />
        <xsl:variable name="docId" select="/doctor/@id" />
        <xsl:value-of select="key('ids',$docId)/hospital/doctors/doctor/name"/>
        ...
      </xsl:template>
   </xsl:stylesheet> 

In my html I can read:

"Doctor identification : doctor's id"

I would like to be able to get :

"Doctor identification : doctor's id doctor's name"

So I've spent a few hours trying to figure out why my xslt code doesn't work. This is an assignment and I have to use the xpath "hospital/records/record". I hope my question is clear enough. Thank you for your help !!!

Upvotes: 0

Views: 32

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

First, change this:

<xsl:variable name="docId" select="/doctor/@id" />

to:

<xsl:variable name="docId" select="doctor/@id" />

Then change this:

<xsl:value-of select="key('ids',$docId)/hospital/doctors/doctor/name"/>

to:

<xsl:value-of select="key('ids', $docId)/name"/>

Hopefully these changes are self-explanatory. Note that the variable is not really necessary: you could do simply:

<xsl:value-of select="key('ids', doctor/@id)/name"/>

Upvotes: 1

Related Questions