[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] get_xpath via Perl, Template Toolkit (XML::Twig)



When parsing XML your xpath statement can say things like:

  'b/c[@jay="rules" and @justin="rules too"]/d'

Which says...
  foreach b node that has a
    child c node that has
       an attribute "jay" set to "rules"
       AND an attribute "justin" set to "rules too"
          and has a child d node

...grab those d nodes.

We were having problems, though. The AND part seemed not to be working deep in the bowels of our real-world scenario inside Template Toolkit.

So I made the simplest possible recreation set, below.

XML::Twig rules.  :)

j



$ cat blah.xml
<a>
 <b>
   <c jay="rules"/>
   <c jay="rules" justin="rules too">
     <d>boo-ya!</d>
   </c>
   <c justin="rules too"/>
 </b>
</a>


$ cat j.pl
#!/usr/bin/perl

use Template;
use XML::Twig;

my $twig = XML::Twig->new( pretty_print => 'indented' );
$twig->parsefile('blah.xml');
$twig = $twig->root;

# -----------------------------
#  Using Perl
# -----------------------------
print "Using Perl:\n";
foreach my $d ($twig->get_xpath('b/c[@jay="rules" and @justin="rules too"]/d')) {
  print $d->text;
}
print "\n\n";

# -----------------------------
#  Using Template Toolkit
# -----------------------------
my $template = Template->new();
$template->process('j.tt', { twig => $twig })
  || die $template->error();


$ cat j.tt
Using Template Toolkit:
[%
FOREACH d IN twig.get_xpath('b/c[@jay="rules" and @justin="rules too"]/d');
     d.text;
  END;
%]


$ perl j.pl
Using Perl:
boo-ya!

Using Template Toolkit:
boo-ya!