in reply to XML::Twig error handling

I am not quite sure I understand the behaviour you are looking for. Could you provide an example of XML and what you would like your code to do with it?

From your post, 'no such attribute' or 'no such XML tag' do not prevent the XML from being well-formed: they would cause the XML not to be valid (against a DTD), but expat is a non-validating parser. So the parser cannot report that kind of error. If the XML is not well-formed, then in any case the parser will stop at the first error. This behaviour is required by the XML spec (fatal error).

Replies are listed 'Best First'.
Re^2: XML::Twig error handling
by ramya2005 (Scribe) on Sep 20, 2005 at 16:55 UTC
    Mirod, Here is an example.
    In the following example I am checking for a tag named 'Filter' and inside the sub I am trying to read 'Name' attribute of the filter tag. What I need is a way to warn the user that the 'Filter' tag that he/she is looking for is not available in the XML provided.... and

    In case the Filter tag is available but not the 'Name' attribute then I need to warn the user about this!
    my $Tree = new XML::Twig ( TwigHandlers => { Filter => sub { my ( $filterTwig, $filter ) = @_; my $filterName = $filter -> att( 'Name' ); $filter -> set_att( Name => "$uniqueFilter" ); } } ); $Tree->safe_parsefile("c:/check.xml"); warn $@ if $@;
    XML
      If I understand correctly (which I'm sure I don't fully), why not set some flag in your handler if the filter name your looking for exists (or save the filter names in a hash?), and then warn or die after the parse if the filter name wasn't there? Or you could warn or die inside the Filter handler if the Name you're looking for isn't there.

      Checking (and warning) that the attribute is missing is easy: add unless( defined $filter->att( 'Name' )) { warn "missing 'Name' attribute\n"; } in the handler.

      To warn that Filter is missing, you will have to set a handler at the next higher level (Filters in this case), and check there that there is a Filter child for the element.

      Alternatively you could write the DTD (or RelaxNg schema) that your tool expects and validate the XML before processing it (using xmllint for example). This way you simplify the code for your tool and it becomes much easier to change the format you expect. Plus having to write the DTD/schema is usually a good thing, it helps getting a proper format.