in reply to XML::Twig - How do I check to see if an element exists in root?

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.

  • Comment on Re: XML::Twig - How do I check to see if an element exists in root?
  • Download Code

Replies are listed 'Best First'.
Re^2: XML::Twig - How do I check to see if an element exists in root?
by dbmathis (Scribe) on Jul 05, 2007 at 04:25 UTC
    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.

        So I am assuming that the first $_ gets populated buy 'map' with the values from 'node'?

        What about the $_ in the hash found? Where does it get its value from?

        I searched for name() on the CPAN page for XML Parser and XML Twig and I could not find it? Where is the subroutine name() coming from.

        This code works but I am still abit confused on the mechanics of it.