in reply to XML::Twig and handles on regex/xpath

Using '//target[@type="aim"]/*' as your xpath:
use XML::Twig; use strict; use warnings; my $data = do {local $/; <DATA>}; my $twig = new XML::Twig(twig_handlers => { '//target[@type="aim"]/*' => sub { print $_->tag, ' ', $_->text, "\n"; }, }); $twig->parse($data); __DATA__ <result> <target type="aim"> <tag1>123</tag1> <tag2>456</tag2> <tag3>234</tag3> </target> </result>

If that pulls too many nodes, you can always filter within the sub.

Replies are listed 'Best First'.
Re^2: XML::Twig and handles on regex/xpath
by Eythil (Acolyte) on Apr 28, 2011 at 08:13 UTC
    That looks fine, but from what I understand it matches everything within target, doesn't it?

    But what if I want to match tag1, tag2 and tag3 but not tag4?
    I guess I should have made a better example.

      Then add the following filter within the sub

      return if $_->tag !~ /^tag[123]$/;
        So I can't really handle it within the xpath expression?!

        But your solutions works totally fine, so I guess I will do it this way.
        I thought it might make a performance difference to call the function, but I can be totally wrong with this thought :-).

        Thank you!