Help required in Splitting a xml file into multiple and appending it in another .xml file

HI All,
I have to split a xml file into multiple xml files and append it in another .xml file. for example below is a sample xml and using shell script i have to split it into three xml files and append all the three xmls in a .xml file. Can some one help plz.

eg:

<?xml version="1.0"?>
<school>
<student id="1">
   <name>john</name>
   <age> 10</age>
</student>
<teacher id="1">
   <name>stella</name>
  <age> 24</age>
</teacher>
<student id="2">
   <name>amy</name>
   <age> 11</age>
</student>
</school>

out put should be 3 xmls and it needs to be appended in a file:

<?xml version="1.0"?>
<school>
 <student id="1">
   <name>john</name>
   <age> 10</age>
 </student>
</school>

<?xml version="1.0"?>
<school>
<teacher id="1">
   <name>stella</name>
  <age> 24</age>
</teacher>
</school>


<?xml version="1.0"?>
<school>
  <student id="2">
   <name>amy</name>
   <age> 11</age>
</student>
</school>
1 Like

I can make code that will work for that exact file but will probably fail for your real application. So it'd be better off to see the actual data you want split in the first place, with confidential parts obscured of course.

1 Like

HI Corona, Thanks for the reply.
Please find the below sample actual xml, in this below example i need to create 4 seperate xmls and update in a .xml file. I will get xml file with only in any of the below four child elements under root element <notificatoin>. " alarmnew, AlarmCleared, AlarmChanged, ackstate" .

<?xml version="1.0"?>
<notification>

<alarmNew sys="abc">
   <Time>2006-04-18T16:04:35</Time>
    <Problem>30425</Problem>
</alarmNew>

<AlarmCleared sys= "xyz">
   <Time>2006-04-18T16:04:35</Time>
  <Problem>30163</Problem>
</AlarmCleared>

<AckState sys= "xyz">
   <Time>2006-04-18T16:04:35</Time>
   <Problem>30163</Problem>
</AckState>

<AlarmChanged sys= "xyz">
    <Time>2006-04-18T16:04:35</Time>
     <Problem>30163</Problem>
</AlarmChanged>

</notification>

Sample output first xml:

<?xml version="1.0"?>
<notification>

<alarmNew sys="abc">
   <Time>2006-04-18T16:04:35</Time>
    <Problem>30425</Problem>
</alarmNew>

</notification>
1 Like
local $/;
my $str = <DATA>;
my @arr = $str =~ /(<(\S+).*?<\/\2>)(?=.*school)/msg;
for(my $i=0;$i<=$#arr;$i=$i+2){
	print '<?xml version="1.0"?>
<school>';
	print "\n";
	print $arr[$i],"\n";
	print "</school>\n\n\n";
}
__DATA__
<?xml version="1.0"?>
<school>
<student id="1">
   <name>john</name>
   <age> 10</age>
</student>
<teacher id="1">
   <name>stella</name>
  <age> 24</age>
</teacher>
<student id="2">
   <name>amy</name>
   <age> 11</age>
</student>
</school>
1 Like
$ awk -F"\n" -v RS="" 'NR>1 && NF>1 { print "<?xml version="1.0"?>\n<notification>\n", $0, "\n</notification>\n\n" > (NR-1)".xml" }' inputfile
1 Like