How can I extract some XML data from a URL using XML::Twig?

女生的网名这么多〃 提交于 2019-12-23 12:42:38

问题


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;

回答1:


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



回答2:


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/



来源:https://stackoverflow.com/questions/1524597/how-can-i-extract-some-xml-data-from-a-url-using-xmltwig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!