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

I have an array that contains a list of words that represent XML elements.

Using XML::Twig how would I do a simple check to see if any of the elements in my array do not exist within my twig root?

I am basically asking the the question "does any of these elements not exist in my XML document? If one does not exist then exit my program?

Is there a simple way of doing. this?
  • Comment on XML::Twig - How do I check to see if an element exists in root?

Replies are listed 'Best First'.
Re: XML::Twig - How do I check to see if an element exists in root?
by Joost (Canon) on Jul 04, 2007 at 23:20 UTC
    By your use of of the word "words" I'm assuming you mean "does the XML document contain one or more elements with the tag name X for each name X in my list"

    something like this would work:

    use strict; use XML::Twig; my @nodes = qw(title toc bar); my %found; my $t = XML::Twig->new( twig_handlers => { map { $_ => sub { $found{$_->name()}++ }; } @no +des } ); $t->parsefile(shift()); # read file specified at command line $t->flush; # update: you may need this for (@nodes) { die "$_ not found" unless $found{$_}; }
    should be reasonably fast, too. For a possibly simpler (and probably slower) approach, you might want to look at the "descendants" method in XML::Twig.

      Joost, fantastic! Worked like a champ! Now I need to spend a few minutes to understand what the following line is doing.

      twig_handlers => { map { $_ => sub { $found{$_->name()}++ }; } @nodes }
        # specify twig_handlers (see the XML::Twig documentation) twig_handlers => { # create a new hash-ref map { # transform a list into a new list # create a name / subroutine pair $_ => sub { # when the subroutine is called # get the element name from $_->name() # and increase it's count entry in %found # # note: $_ is set by XML::Twig when the sub is called $found{$_->name()}++ }; } @nodes # for each element in @nodes }

        See also map.