user4128379
user4128379

Reputation:

Handling the xml parser error

I have lots of XML files that I have to read them and then see if they are valid or not. I have some files that have problem withe missing endtag. Now my task is to write a code that read these files and just print the error message and the name of file when there is invalid file and go to the next file.

I am new to Perl and XML. But if I know how to handle there is entag error then I could do rest. What I know is that I have such a line in the code and reads the XML files and then looks for the parsering. If is not OK then will produce an error in command line. My aim is to have a condition and then I will write a message.

 use strict;
 use warnings;
 use XML::LibXML;
 use XML::Simple;
 use XML::LibXML::XPathContext qw( );
 use XML::Writer;

 # reads all file
 my @testFile = <*.xml>;

 my $arrSize = @testFile;
 XML::LibXML::XPathContext->new()
 my $doc = XML::LibXML->load_xml(location => $ver);
 my $name_ver = $xml->findnodes('/Info/Name',$doc);
 ##  do some other things

I hope this is somehow is clear what I mean. Can anyone please let me know how could I write a condition that does not allow the code to stop, rather goes to other line and print a message.

Upvotes: 2

Views: 1972

Answers (1)

Sobrique
Sobrique

Reputation: 53498

Wrap your parse operations in an eval, and trap $@.

Using a library I know better:

#!/usr/bin/env perl
use strict;
use warnings; 
use XML::Twig; 

foreach my $file ( glob "*.xml") {
     eval { XML::Twig -> new() -> parsefile ( $file ) }; 
     if ( $@ ) { 
          print "$file not valid XML: $@\n"; 
     }
     else {
          print "$file parsed successfully\n";
     }
}

This approach should work with most XML parsers in Perl, so is just illustrative. By design and spec, broken XML is supposed to be a fatal error.

Upvotes: 6

Related Questions