<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="xml"/>

<xsl:template match="*">
   <xsl:copy>
      <xsl:apply-templates/>
   </xsl:copy>
</xsl:template>

<xsl:template match="/">
   <xsl:for-each select="*/instructor">
      <xsl:copy>
         <xsl:for-each select="@*"><xsl:copy/></xsl:for-each>

         <xsl:apply-templates/>

         <xsl:variable name="tmp" select="@teaches"/>

         <xsl:for-each select="following::course[contains($tmp, @cid)]">
            <xsl:element name="teaches">
               <xsl:copy>
                  <xsl:apply-templates/>
               </xsl:copy>
            </xsl:element>
         </xsl:for-each>

         <xsl:for-each select="preceding::course[contains($tmp, @cid)]">
            <xsl:element name="teaches">
               <xsl:copy>
                  <xsl:apply-templates/>
               </xsl:copy>
            </xsl:element>
         </xsl:for-each>

      </xsl:copy>
   </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

