OK, let's clear some misconceptions about XML::Twig with some explanations and a bit of code (I'll add this to the doc of the module for next version):
- if you are using twig_roots then the tree will be composed only of the document root, the twig_roots elements and all of their sub-elements,
- twig_handlers on the other hands do not impact the way the tree is built, the handler is called as soon as the element is completely parsed, and the entire tree that has been built previously, including all of the element sub-elements is accessible...
- except when when you use either flush or purge: in this case the module will delete as much of the tree as can possibly be, which means that only the direct ancestors of the current element will remain, each with one single child.
Now for something completely similar:
#!/bin/perl -w
use strict;
use XML::Twig;
my $doc=
'<doc>
<l1>
<l2>
<e1>e1</e1>
<e2>e2</e2>
<e3>e3</e3>
</l2>
</l1>
</doc>';
my $twig= new XML::Twig( twig_roots => { l2 => 1 }
twig_handlers => { e2 => \&e2}
);
$twig->parse( $doc);
sub e2
{ my( $t, $e2)= @_;
print "ancestors: ";
print map { $_->gi . " " } $e2->ancestors; # print l2 doc
print "\n";
print "siblings: ";
print $e2->prev_sibling->gi; # print e1
print " no next sibling\n" unless $e2->next_sibling; # e3 is not t
+here yet
print "purge!\n";
$t->purge;
print "ancestors: ";
print map { $_->gi . " " } $e2->ancestors; # print l2 doc (still
+ there)
print "\n";
print "siblings: ";
print " no prev sibling\n" unless $e2->prev_sibling; # e1 is gone
print " no next sibling\n" unless $e2->next_sibling; # e3 is still
+ not there
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.