Check the xml files for valid content

Check that the xml files in a directory are well formed and valid.

#!/usr/bin/perl
# J C
# -------------------------------------------------------------------------
# 10/8/2008 -   XML parser to check validity of documents
# OUTPUT : errors.txt a file containing the error messages for each file that failed to parse.
# Each file that failed to validate has the extension "_invalid.xml" so that it can be manually chacked for bad tokens or missing tags.
#--------------------------------------------------------------------------


use XML::Checker::Parser;


opendir(DIR, ".");
@files = readdir(DIR) or die $!;
closedir(DIR);
print "checking\n" ; 

open OUTFILE, ">>errors.txt" or die $!;
foreach $filename (@files)
{
 if (($ext) = $filename =~ m/\.(xml|XML)$/)
 {
  $filename =~ m/(.+)\.\w{3}/;
  my $xp = new XML::Checker::Parser ( Handlers => { } );

 eval {
 $xp->parsefile($filename);
  };
 if ($@) {

  print "$xml_file $filename failed validation!\n";
  print OUTFILE "$filename ------- ERROR";
  rename($filename , $filename."_invalid.".$ext ) ; 
  print OUTFILE "$@\n";
  }
  else {
  print "$xml_file $filename passed validation\n";
  }
 }

}

close(OUTFILE);

Comments

Popular posts from this blog

Find countries in a file's text using regular expressions and Perl

Make links active in Excel 2007