0

I seem to have problem retrieving the value of a node when the node name is the value of another node in the same document. Let me illustrate.

First the document:

<?xml version="1.0" encoding="UTF-8"?>
<Doc>
    <Schools>
        <School>
            <Id>5489</Id>
            <Name>St Thomas</Name>
            <Address>High Street, London, England</Address>
        </School>
        <School>
            <Id>7766</Id>
            <Name>Anderson Boys School</Name>
            <Address>Haymarket, Edinborough</Address>
        </School>
    </Schools>
    <FamilySmith>
        <Children>
            <Child>
                <Name>Thomas</Name>
                <School_Id>5489</School_Id>
            </Child>
            <Child>
                <Name>Andrew</Name>
                <School_Id>7766</School_Id>
            </Child>
        </Children>
    </FamilySmith>
</Doc>

I simply want to display the following: Thomas goes to St Thomas at High Street, London, England. Andrew goes to Anderson Boys School at Haymarket, Edinborough

Using the folollowing xsl:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
        <xsl:output method="text"/>

        <xsl:template match="/Doc">
        <xsl:apply-templates select="FamilySmith"/>
    </xsl:template>

    <xsl:template match="FamilySmith">
        <xsl:for-each select="Children/Child">
            <xsl:text>&#xa; </xsl:text>
            <xsl:value-of select="Name"/>
            <xsl:text> goes to </xsl:text>
            <xsl:value-of select="/Doc/Schools/School[Id = School_Id]/Name"/>
            <xsl:text> at </xsl:text>
            <xsl:value-of select="/Doc/Schools/School[Id = School_Id]/Address"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

But it seems that the expression /Doc/Schools/School[Id = School_Id]... does not work as it returns an empty value each time. The results are given below.

Thomas goes to at Andrew goes to at

Any offers pleaese? Thanks.

Bumblevee
  • 69
  • 1
  • 5

1 Answers1

0

You are looking for the current() function:

<xsl:value-of select="/Doc/Schools/School[Id = current()/School_Id]/Name"/>

Your previous attempt was looking for School elements that have an Id and a School_Id child that have the same value, whereas what you actually want is to compare the School's Id against the School_Id child of the Child that is the target of the current iteration of the for-each, i.e. the current context node from outside the predicate. This is what current() gives you.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183