Wednesday, 19 March 2014

Pivot xml to another xml  
/redefine the tree structure of xml


Pivot.XSL
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:key name="muench" match="/bar/part " use="@id"/>
<xsl:template match="/">
<bar>
<xsl:for-each select="/structure/r[generate-id() = generate-id(key('muench',@id)[1])]">
<xsl:call-template name="pivot">
<xsl:with-param name="key" select="@id"/>
</xsl:call-template>
</xsl:for-each>
</bar>
</xsl:template>
<xsl:template name="pivot">
<xsl:param name="key"/>
<series key="{$key}">
<xsl:for-each select="/bar/part[@id=$key]">
<xsl:copy-of select="."/>
</xsl:for-each>
</series>
</xsl:template>
</xsl:stylesheet>

Input XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<bar>
    <part id='1' count='1' bad='1'/>
    <part id='2' count='2' bad='2'/>
    <part id='3' count='3' bad='3'/>
    <part id='4' count='4' bad='4'/>
    <part id='5' count='5' bad='5'/>
    <part id='6' count='6' bad='6'/>
    <part id='7' count='10' bad='7'/>
    <part id='8' count='20' bad='8'/>
    <part id='9' count='10' bad='9'/>
    <part id='10' count='20' bad='10'/>
  </bar>
  
Output XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<bar>
    <part id='1' count='1' bad='1'/>
 </bar>
<bar> 
  <part id='2' count='2' bad='2'/>
 </bar>
<bar>
    <part id='3' count='3' bad='3'/>
 </bar>
<bar>
<part id='4' count='4' bad='4'/>
 </bar>
<bar>
    <part id='5' count='5' bad='5'/>
 </bar>
<bar>
    <part id='6' count='6' bad='6'/>
 </bar>
<bar>
    <part id='7' count='10' bad='7'/>
 </bar>
<bar>
    <part id='8' count='20' bad='8'/>
 </bar>
<bar>
    <part id='9' count='10' bad='9'/>
 </bar>
<bar>
    <part id='10' count='20' bad='10'/>
 </bar>

No comments:

Post a Comment