in reply to Re: XML::Twig error handling
in thread XML::Twig error handling

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
In the following example when <Filter Name="IP"/> is not available Is there a way to get a warning or error?
<?xml version="1.0" encoding="UTF-8"?> <Settings Version="1.0"> <Name>Capture</Name> <Buffer Size="16777216"/> <Filters Mode="Accept"> <Filter Name="IP"/> </Filters> </Settings>

Replies are listed 'Best First'.
Re^3: XML::Twig error handling
by runrig (Abbot) on Sep 20, 2005 at 17:30 UTC
    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.
Re^3: XML::Twig error handling
by mirod (Canon) on Sep 21, 2005 at 08:56 UTC

    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.