Below is a Perl script to create xml messages based on a template. It takes two files as input: an xml template and a list of values to put into the template. The values file consist of any number of lines with the following format: message number;element name; value. So you can choose how many xml messages you want to create and how many elements you want to fill in per message.
The script as such works, but this is one of my first actual Perl scripts. So any advice on what I could have done better is more than welcome. For instance, the way I use $lastreqnr as the upper limit of the for loop, feels more like a hack than a decent solution.
use warnings; use strict; use Data::Dumper; #configuration - to make using different templates etc. more easy my $xmltpl = "xmltpl.xml"; # xml template my $changes = "values.txt"; # values to be filled in my $reqname = "LoB_GPDLI"; # common part of request names #to avoid error message because of use strict my $slncnt=0; my %sfile = (); my $num=0; my $lastreqnr=0; my $i=0; my $req=(); # open file with the values and put into an hash of arrays open (my $fh1, "$changes"); my @arfile = <$fh1>; foreach my $arline (@arfile) { $slncnt++; my $sname = "sline" . "$slncnt"; chomp($arline); my @sline = split (/;/, $arline); $sfile{$sname} = [ @sline ]; $lastreqnr = $sfile{$sname}[0]; } # to check if the values file values has been read properly print "Total number of lines of changes is $slncnt\n"; print "Last req number is $lastreqnr\n"; print "\n"; # read the xml template, create a request file # and put in all the changes from the value file. for($i=1; $i <= $lastreqnr; $i++) { $num = 0; my $reqfile = "$reqname" . "_" . "$i" . ".xml"; print "reqname is $reqfile\n"; if (-e "$reqfile") { die "$reqfile already exists."; } open (my $req, ">>$reqfile") or die "Could not create req file"; open (my $tpl, "$xmltpl") or die "Could not open file"; while (<$tpl>) { my $tplln = $_; chomp $tplln; foreach my $group (keys %sfile) { if ($sfile{$group}[0] == $i) { $tplln =~ s{$sfile{$group}[1]}{$sfile{$group}[2]}; } } print $req $tplln; } close ($req) or die "Could not close request"; close ($tpl) or die "Could not close template"; print "\n"; } close ($fh1) or die "Could not close fh1";
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |