Q:

How can I map two side by side XML structures together via XSLT?

I am getting an XML file that I need to translate into another standard type. I have XSLT2 at my fingertips, and I can't control the format of either file.  The first one has two sequences that use a number value to match them up.  The first sequence could have 0..n of the second.
An example is:
Input:
<foo>
<structure name="items">
    <item>
        <itemCode>1</itemCode>
        <itemValue>1111</itemValue>
    </item>
    <item>
        <itemCode>2</itemCode>
        <itemValue>2222</itemValue>
    </item>
</structure>
<structure name="subItems">
    <subItem>
        <itemCode>1</itemCode>
        <subValue>12</subValue>
        <subType>MISC</subType>
    </subItem>
    <subItem>
        <itemCode>1</itemCode>
        <subValue>15</subValue>
        <subType>MISC2</subType>
    </subItem>
    <subItem>
        <itemCode>2</itemCode>
        <subValue>40</subValue>
        <subType>MISC</subType>
    </subItem>
</structure>
</foo>

And the output I want is 
<bar>
<items>
    <item>
        <code>1</code>
        <value>1111</value>
        <subItems>
            <subItem>
                <subValue>12</subValue>
                <subType>MISC</subType>
            </subItem>
            <subItem>
                <subValue>15</subValue>
                <subType>MISC2</subType>
            </subItem>              
        </subItems>
    </item> 
    <item>
        <code>2</code>
        <value>2222</value>
        <subItems>
            <subItem>
                <subValue>40</subValue>
                <subType>MISC</subType>
            </subItem>
        </subItems>
    </item>         
</items>
</bar>

I have been unsuccessful mapping the item.itemCode to subItem.itemCode simply because the XSLT processor seems to exit the first sequence before seeing the next.  I have no way to know how many I will get in either sequence, so I can't do a static map.
Any ideas?
Thanks in advance

A:

Another method to select the proper subvalues is to use a key:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  
  <xsl:key name="subitems-by-code" match="subItem" use="itemCode"/>

  <xsl:template match="foo">
    <bar>
      <items>
        <xsl:apply-templates select="structure[@name='items']"/>
      </items>
    </bar>
  </xsl:template>

  <xsl:template match="item">
    <item>
      <xsl:copy-of select="*"/>
      <subItems>
        <xsl:apply-templates select="key('subitems-by-code', itemCode)"/>
      </subItems>
    </item>
  </xsl:template>

  <xsl:template match="subItem">
    <subItem>
      <xsl:copy-of select="subValue|subType"/>
    </subItem>
  </xsl:template>
</xsl:stylesheet>

