Hi Jon,
On Sat, 3 Dec 2011 16:52:25 -0700
Jon Forsyth <[email protected]> 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:
>
Well, I'm not intimately familiar with XML::Twig (as I prefer XML::LibXML and
recently also started maintaining it), but I think I know how to help you.
> <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
You should give different callbacks for 'title' and 'subtitle' (unless you have
some way to distinguish between them). You can also use a closure:
[CODE]
'title' => sub { return handle_elem('title', @_); },
'subtitle' => sub { return handle_elem('subtitle', @_; },
[/CODE]
> }
> );
> $t->parsefile( 'doc.xml');
>
> sub writeDBrow
> { my( $t, $elt)= @_;
> print $elt->text; # print the text (including sub-element texts)
>
Here you need to assign the $elt->text() to a variable instead of printing it.
See:
http://perl-begin.org/ .
Regards,
Shlomi Fish
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Funny Anti-Terrorism Story - http://shlom.in/enemy
If it isn’t in my email, it doesn’t exist.
And if the whole world says one thing and my email says something different,
email will conquer.
— an Israeli Linuxer.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/