http://qs321.pair.com?node_id=814569

valavanp has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
Open a directory and read all the files, based on certain criteria the an xml file should be generated. The following example is only for 2 files whereas i have multiple files to generate the xml. The xml structure should if there is no date or no pid it should not create any tags., where as it is creating for all the dates. The directory and the file structure:
/test/filename_12345_010107_ABC.txt /test/filename_12345_010207_ABC.txt /test/filename_12345_020107_zzz.txt /test/filename_12345_020207_zzz.txt /test/filename_55555_010107_ABC.txt /test/filename_55555_010207_ABC.txt /test/filename_55555_020107_ABC.txt /test/filename_55555_020207_zzz.txt The xml file should be: <pt id="12345"> <date id="010107"> <abc id="abc" url="abc.html"></abc> <zzz id=""zzz" url="zzzz.html"></zzz> </date> </pt> <pt id="55555"> <date id="010107"> <abc id="abc" url="abc.html"></abc> </date> </pt>
The code for that:
#!/usr/bin/perl use XML::Simple; use XML::Writer; use IO::File; my %pt; my %dates; my %abcs; $dirname="test"; $output = new IO::File(">>out_file.xml"); $counter=1; opendir(DIR, $dirname) || die "Error in opening dir $dirname\n"; while(($filename = readdir(DIR))){ next if($filename eq '.' or $filename eq '..' ); ($unwanted,$unwanted,$pid,$env,$date)=split("_",$filename); chomp($date,$pid,$env); $date=~ s/^\s+//g; $date==~ s/\s+$//g; $date=~ s/\.txt//g; $projects{$pid}=[] unless exists $projects{$pid}; $dates{$date}=[] unless exists $dates{$date}; $envs{$env}=[] unless exists $envs{$env}; #push @{$projects{$pid}}, $date; #$push @{$dates{$date}}, $env; } foreach $pid(sort keys %projects){ $writer=new XML::Writer(OUTPUT => $output); if($pid==""){ }else{ $writer->startTag("pt",id=>$pid); foreach $date(sort keys %dates){ if($date==""){ }else{ $writer->startTag("date",id=>$date); foreach $env(sort keys %envs){ print $env; if($env eq ""){ }elsif($env eq "ABC"){ $writer->startTag("sit",url=>$env); $writer->endTag(); }elsif($env eq "ZZZ"){ $writer->startTag("uat",url=>$env); $writer->endTag(); } } $writer->endTag(); } } $writer->endTag(); } closedir(DIR);
The result of the xml file should be if there is no date existence, than it should not create any xml tags whereas the current code generates the xml for all dates which is wrong. The output which i am getting for the above code is
<pt id="12345"> <date id="010109"> <sit s_name="ABC"></sit> <uat u_name="ZZZ"></uat> </date> <date id="020109"> <sit s_name="ABC"></sit> <uat u_name="ZZZ"></uat> </date> </project> <project id="55555"> <date id="010109"> <sit s_name="ABC"></sit> <uat u_name="ZZZ"></uat> </date> </project>