On 03/12/2011 23:52, Jon Forsyth wrote:
Dear Beginners List,
My code is based on an example from the XML::Twig documentation. I want to
capture the text of a couple elements that have descendant elements and put
this text in separate variables (one for each element's text). The problem
in the code example is that all the text of the lower elements is returned
in a 'print'. So to illustrate:
<title>text # I want this piece of text saved in one
variable
<subtitle>more text # and this piece of text stored in another
variable
<p>some more text</p> # without getting this
</subtitle>
</title>
Code:
---------------------------------------------
use strict;
use warnings;
use XML::Twig;
my $t= XML::Twig->new(
# the twig will include just the root and selected titles
twig_roots => { 'title' => \&writeDBrow,
'subtitle' => \&writeDBrow
}
);
$t->parsefile( 'doc.xml');
sub writeDBrow
{ my( $t, $elt)= @_;
print $elt->text; # print the text (including sub-element texts)
# Insert Code to write to a Database here
$t->purge; # frees the memory
}
---------------------------------------------
Using XML::Twig like this - with event handlers - is useful only if the
data source is huge and you require only parts of it in memory at one
time. Since your root element is <title> and you have specified this in
a 'twig_root' handler it will read the entire document anyway, so you
may as well just parse the entire file and navigate the tree.
The 'text' mehod on its own will, as you have discovered, return all the
text child nodes of the element and any of its descendants. To avoid
looking beyond the element's immediate children, pass the option
'no_recurse'. Furthermore, using the 'trimmed_text' method will remove
any unwanted whitespace, including trailing newlines, that were only
there to make the original XML look nice.
The program below shows these ideas.
HTH,
Rob
use strict;
use warnings;
use XML::Twig;
my $t= XML::Twig->new;
$t->parse(\*DATA);
my $title = $t->root;
my $subtitle = $title->first_child('subtitle');
print $title->trimmed_text('no_recurse'), "\n";
print $subtitle->trimmed_text('no_recurse'), "\n";
__DATA__
<title>
text
<subtitle>
more text
<p>some more text</p>
</subtitle>
</title>
**OUTPUT**
text
more text
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/