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

Hi Monks!
I am parsing XML files and sometimes some of these XML files will come not well formatted causing a Software Error on the browser page, I am trying to print an error other than that by trapping this error if it happens, but I can't get the code to work, may some of you would help by looking into my code here, or show me a better way of doing this.
Here is the code:

# ... this is the part of the code I am trying to make work my $xp; # initialize parser object and parse the string $xp = XML::XPath->new( ErrorContext => 2 ); eval { $xp->parsefile( $open_this ); }; # $open_this is the xml file # report any error that stopped parsing if( $@ ) { $@ =~ s/at \/.*?$//s; # remove module line number print STDERR "\nERROR::: $open_this isn't well formated file:\n$@\ +n"; } ...


Thank you!

Replies are listed 'Best First'.
Re: Trapping XML error using Perl
by psini (Deacon) on Jun 13, 2008 at 18:53 UTC

    ... and the problem is ... ?

    Does it work? throw an error? Works only on some cases?

    Please give us some more clues.

    Careful with that hash Eugene.

      It does, if the xml file is not well formatted, like:

      Software error: unclosed token at line 1810, column 6, byte 65534: <Car>N</Car> <Bus>N</Bus> < =====^ at C:/Perl/lib/XML/Parser.pm line 187 For help, please send mail to this site's webmaster, giving this error + message and the time and date of the error.


      That's what I don't want, I want to get the error before and skip this file, and not display it to the user.

        I'm afraid that you can't do that with XML::Parse because it dies on malformed XML.

        On the other hand try and see XML::SAX and XML::SAX::Exception. I think they can help you

        Careful with that hash Eugene.