2

Source XML:

    <record>
       <protein>AAA</protein>
       <reference>1234</reference>
       <reference>679</reference>
    </record>
    <record>
       <protein>BBB</protein>
       <reference>9876</reference>
    </record>
    <record>
       <protein>CCC</protein>
       <reference>9876</reference>
       <reference>14846</reference>
       <reference>982</reference>
    </record>

I am new at using XLST and have been unable to find a solution to my problem. I need to specifically create an XML file where the data in a record is split out into one or more new records based upon the values in a list. Please note that the number of values in the list (reference) is highly variable.

Desired XML:

    <record>
       <protein>AAA</protein>
       <reference>1234</reference>
    </record>
    <record>
       <protein>AAA</protein>
       <reference>679</reference>
    </record>
    <record>
       <protein>BBB</protein>
       <reference>9876</reference>
    </record>
    <record>
       <protein>CCC</protein>
       <reference>9876</reference>
    </record>
    <record>
       <protein>CCC</protein>
       <reference>14846</reference>
    </record>
    <record>
       <protein>CCC</protein>
       <reference>982</reference>
    </record>

Any help is much appreciated.

Lukasz
  • 7,572
  • 4
  • 41
  • 50
Pat Bacha
  • 21
  • 2
  • You may want to see a generic solution to the "shredding problem" in my answer to this question: http://stackoverflow.com/a/8597577/36305 – Dimitre Novatchev Feb 13 '12 at 17:28

1 Answers1

1

I have to adjust you sample XML input file.

<?xml version="1.0" encoding="UTF-8"?>
<records>
<record>
       <protein>AAA</protein>
       <reference>1234</reference>
       <reference>679</reference>
</record>
<record>
       <protein>BBB</protein>
       <reference>9876</reference>
</record>
<record>
       <protein>CCC</protein>
       <reference>9876</reference>
       <reference>14846</reference>
       <reference>982</reference>
</record>
</records>

Then, the XSL itself may look like this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" >
<xsl:output exclude-result-prefixes="xsl xs" indent="yes"/>
<xsl:template match="/records/record">
    <xsl:for-each select="reference">
        <xsl:element name="record">
           <xsl:element name="protein">
               <xsl:value-of select="../protein/text()"/>
           </xsl:element>
           <xsl:element name="reference">
               <xsl:value-of select="text()"/>
           </xsl:element>
        </xsl:element>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Lukasz
  • 7,572
  • 4
  • 41
  • 50