2

I would like to split a file in to several files based on the starting letter of an element. For example:

 <Employees>      
 <Employee id="1"> 
 <firstname value="Atif"></firstname>           
 <lastname value="Bashir"></lastname>           
 <age >32</age>           
 </Employee>      
 <Employee id="2"> 
 <firstname value="xyz"></firstname>           
 <lastname value="abc"></lastname>           
 <age >32</age>           
 </Employee>      
 <Employee id="3"> 
 <firstname value="abc"></firstname>           
 <lastname value="none"></lastname>           
 <age >32</age>           
 </Employee>      
 </Employees> 

After applying transformation, the above file should be split into two files because the first character of Employee/firstname[@value] (and group all the data). So for above case first file should be:

a.xml

 <Employees>      
 <Employee id="1"> 
 <firstname value="Atif"></firstname>           
 <lastname value="Bashir"></lastname>           
 <age >32</age>           
 </Employee>      
 <Employee id="3"> 
 <firstname value="abc"></firstname>           
 <lastname value="none"></lastname>           
 <age >32</age>           
 </Employee>      
 </Employees> 

and the second file should be:

x.xml

 <Employees>      
 <Employee id="2"> 
 <firstname value="xyz"></firstname>           
 <lastname value="abc"></lastname>           
 <age >32</age>           
 </Employee>      
 </Employees>      

What is the XSLT code to perform this transformation?

Thank you!

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
atif
  • 1,137
  • 7
  • 22
  • 35

2 Answers2

3

With XSLT 2.0:

<xsl:for-each-group select="Employee" 
                    group-by="lower-case(substring(firstname,1,1))">
  <xsl:result-document href="{current-grouping-key()}.xml">
    <xsl:copy-of select="current-group()"/>
  </xsl:result-document>
</xsl:for-each-group>
Michael Kay
  • 156,231
  • 11
  • 92
  • 164
0

If you are using XSLT 2.0, look into <xsl:result-document>.

If you are using XSLT 1.0, you need an extension element, such as <exsl:document>.

More clues:

Community
  • 1
  • 1
mzjn
  • 48,958
  • 13
  • 128
  • 248