tags:

views:

47

answers:

2

Hi, I have the following XML file:

<phonebook>
    <departments>
     <department id="1" parent="" title="Rabit Hole" address="" email="" index=""/>
     <department id="2" parent="" title="Big Pond" address="" email="" index=""/>
    </departments>
    <employees>
     <employee id="1" fname="Daffy" lname="Duck" title="Admin" email="[email protected]" department="2" room="" />
     <employee id="2" fname="Bugs" lname="Bunny" title="Programmer" email="[email protected]" department="1" room="" />
    </employees>
</phonebook>

When displaying it, I want to show the contact details for an employee as well as the title of the department where he works. Here's what I've got in the template:

<xsl:for-each select="phonebook/employees/employee">
    <xsl:sort select="@lname" />
    <tr>
     <td>
      <span class="lname"><xsl:value-of select="@lname"/></span>
      <xsl:text> </xsl:text>
      <span class="fname"><xsl:value-of select="@fname"/></span>
     </td>
     <td><xsl:value-of select="@title"/></td>
     <td>
      <xsl:value-of select="/phonebook/departments/department[@id='{@department}']/@title"/>
     </td>
     <td><a href="mailto:{@email}"><xsl:value-of select="@email"/></a></td>
    </tr>
</xsl:for-each>

The problem is that the following rule doesn't seem to work:

<xsl:value-of select="/phonebook/departments/department[@id='{@department}']/@title"/>

I guess this is because the XSLT engine looks for the department property in the department element, and not in the employee element. However, I don't have an idea how to fix it. Could anyone give me a hint on that?

+2  A: 

The {} in the select are not supported, I prefer using a variable, but anothor option would be using current(). But I would probably just use something like:

<xsl:variable name="departmentId" select="@department" />
<xsl:value-of select="/phonebook/departments/department[@id=$departmentId]/@title"/>
jor
Doh! I tried using a variable, and it didn't work. But copy-pasted from your example, it does. Thanks! :)
Rimas Kudelis
+3  A: 

Lots of ways, but a nice reusable one is to use a key.

Definition:

<xsl:key name="dept" match="/phonebook/departments/department" use="@id"/>

Usage (where the current node is an <employee>:

<xsl:value-of select="key('dept', @department)/@title"/>
annakata
Please, *simplify* your <xsl:key>. One can use just: match="department" . As a matter of fact, the value of the "match" attribute is a *match pattern*, something quite simpler than a more complete XPath expression.
Dimitre Novatchev