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

I'm getting this error because now and then there are duplicate xml values in a file I'm reading. The code dies when it hits this. Instead, I'd like to skip the file when this happens, not die. How can I trap this error?
Thanks! Details:
My xml looks like: <record value1="1" value1="2"... My code is: my $value = $record1->getAttribute('value1'); The error that happens is: duplicate attribute at line 7, column 2, byte 167 at /Library/Perl/5.8 +.6/darwin-thread-multi-2level/XML/Parser.pm line 187

Replies are listed 'Best First'.
Re: Catch XML error
by Joost (Canon) on Jul 14, 2007 at 00:19 UTC
    The post above will give you an answer to your problem. Now I'm trying to persuade you from solving the problem in the way you want.

    XML documents have a very strictly defined format. All conforming parsers will throw an exception for the input you describe, because the input is not XML and the "correct" thing to do is to reject the whole input file.

    This makes sense when you use XML to transfer data between systems - you generally don't know much about the sending system, and if the input doesn't conform to the specs, the right attitude to take is that the other system has just thrown a bug or the stream has been mangled during transfer.

    Again; your input is not XML. Trying to subvert the XML specs is fine by me, but you should not expect any standard XML tools to help you do it, and other developers/spec-writers will probably not understand all the subtleties involved. The full XML spec really is not as easy as you'd think from reading a couple of XML files. If you're diverting from it, you'd better make really sure you know what you're doing.

      fair. It's a headless app sitting on a remote box. I need to know if it's getting an error (dies to a function that shoots me a note). Not subverting, just doing better error handling to know if something bad this way came-ith.
Re: Catch XML error
by philcrow (Priest) on Jul 13, 2007 at 20:44 UTC
    Try wrapping in eval:
    my $value; eval { $value = $record1->getAttribute('value1'); }; next FILE if ( $@ );

    Note the scope. Define the variable outside the eval, or you'll only be able to use it in the block.

    Phil

    The Gantry Web Framework Book is now available.

      Note that the eval will catch all errors, not just this one. It might be prudent to look at the contents of $@ (see perlvar) to see if the error you caught is really the one you want to skip silently.

      my $value; eval { $value = $record1->getAttribute('value1'); }; if ( $@ ) { next FILE if ( $@ =~ /^duplicate attribute/ ); die $@; }