tags:

views:

180

answers:

2

I want to get a specific string, for example 123 in <received>123</received> from some XML that will be retrieved from a URL.

I have write a code but stuck with an error message:

Attempt to bless into a reference at /usr/share/perl5/XML/Twig.pm line 392.

How can I solve it?

The code:

use XML::Twig;
use LWP::Simple;

my $url = 'http://192.168.1.205:13000/status.xml';
my $twig = new XML::Twig(TwigRoots => {
'smsc/received' => sub {$author = $_[1]->text;  }});
$twig->nparse( $url );
$twig->print;
+3  A: 

Appears to be a bug in nparse method because if you replace that line with:

$twig->parse( LWP::Simple::get($url) );

Then you should find it works fine (or it does when I try it).

/I3az/

draegtun
it's not a bug in nparse, it's a bug in the way it's called ;--)
mirod
Ah yes... I can see it explicitly in your POD now! Retested my example here and it works brilliantly now: my $twig = XML::Twig->nparse( twig_handlers => { title => sub { print $_->text },}, 'http://w3c.org');
draegtun
in fact nparse and xparse were kinda failed experiments, which eventually lead me to the simple rewriting of parse to take care of everything for you (new _and_ determining the kind of parse to use)
mirod
@mirod: Let me take this gushy moment to say a sincere "thank you" for XML::Twig. Its been a enjoyable, powerful and sometimes life saving tool over the years. Yours Barry
draegtun
PS. Thats "life saving" in terms of getting the work out despite the other $work issues ;-)
draegtun
@draegtun thanks, I quite like working on it too.
mirod
Tried thed code before however it seems fail to work with TwigRoots.
conandor
I was just commenting on nparse bit to get you past that hurdle. I noticed there was other things in your code that needs addressing... Mirod's answer covers these.
draegtun
+4  A: 

nparse takes care of the new for you (hence the 'n'), what you want in this case is probably xparse, or just let the module figure it out and do this:

my $url= 'http://192.168.1.205:13000/status.xml';
my $twig= XML::Twig->parse( twig_roots => 
                              { 'smsc/received' => sub { $author= $_[1]->text;}},
                             $url
                           );
$twig->print; # I am not sure why you print the twig instead of just $author
mirod
Thanks mirod. It works well with xparse. FYI, the $twig->print is just for debugging use. Actually I just want value $author.
conandor