简体   繁体   English

如何在Perl中获取xml值?

[英]How do i get an xml value in perl?

Im a beginner to perl and i have a problem that I don't know how to solve. 我是perl的初学者,我有一个我不知道如何解决的问题。 Im trying to fetch xml-data from a website and put the value of temperature in an array. 我试图从网站获取xml数据并将温度值放入数组中。

This is my code so far: 到目前为止,这是我的代码:

use strict;
use warnings;

# For parsing
use XML::Simple;

# For downloading
use LWP::Simple;

# For debug output
use Data::Dumper;

# Turn off output buffering
$|=1;

# Note, no error checking here!

sub main 
{

    print "\nDownloading ....";
    my $data = get('http://www.yr.no/place/Norway/Telemark/Sauherad/Gvarv/forecast_hour_by_hour.xml');

    my $parser = new XML::Simple;

    print "\nParsing ...";
    my $dom = $parser->XMLin($data);

    print "\n\n";

    # Debug output. 
    #print Dumper($dom->{'forecast'});

    # Data structure is a hash containing one key, 'entry'.
    # Get the hash value and cast to an array.
    my @entries = $dom->{'forecast'}->{'tabular'}->{'time'};
    # Go through each array 'entry' element.
    foreach my $entry(@entries) 
    {   
        print Dumper($entry);
        # Each element is a hash.
        # The band name can be got from one hash key.
        my $tabular = $entry->{'temperature'};


        #print "$tabular\n";


        print "\n\n";
    }


}

main();

And the output that I get on my terminal is: 我在终端上得到的输出是:

    },
      {
        'temperature' => {
                         'unit' => 'celsius',
                         'value' => '26'
                       },
        'windSpeed' => {
                       'name' => 'Light breeze',
                       'mps' => '1.9'
                     },
        'to' => '2016-08-17T16:00:00',
        'pressure' => {
                      'unit' => 'hPa',
                      'value' => '1014.1'
                    },
        'from' => '2016-08-17T15:00:00',
        'precipitation' => {
                           'value' => '0'
                         },
        'symbol' => {
                    'numberEx' => '1',
                    'var' => '01d',
                    'number' => '1',
                    'name' => 'Clear sky'
                  },
        'windDirection' => {
                           'name' => 'North',
                           'code' => 'N',
                           'deg' => '4.4'
                         }
      },
      {
        'precipitation' => {
                           'value' => '0'
                         },
        'from' => '2016-08-17T16:00:00',
        'windDirection' => {
                           'name' => 'North-northeast',
                           'code' => 'NNE',
                           'deg' => '20.6'
                         },
        'symbol' => {
                    'number' => '1',
                    'name' => 'Clear sky',
                    'var' => '01d',
                    'numberEx' => '1'
                  },
        'temperature' => {
                         'unit' => 'celsius',
                         'value' => '27'
                       },
        'pressure' => {
                      'value' => '1013.4',
                      'unit' => 'hPa'
                    },
        'to' => '2016-08-17T17:00:00',
        'windSpeed' => {
                       'mps' => '1.2',
                       'name' => 'Light air'
                     }
      },
      {
        'symbol' => {
                    'numberEx' => '1',
                    'var' => '01d',
                    'name' => 'Clear sky',
                    'number' => '1'
                  },
        'windDirection' => {
                           'name' => 'East',
                           'code' => 'E',
                           'deg' => '83.0'
                         },
        'from' => '2016-08-17T17:00:00',
        'precipitation' => {
                           'value' => '0'
                         },
        'windSpeed' => {
                       'mps' => '0.7',
                       'name' => 'Light air'
                     },
        'pressure' => {
                      'unit' => 'hPa',
                      'value' => '1012.8'
                    },
        'to' => '2016-08-17T18:00:00',
        'temperature' => {
                         'unit' => 'celsius',
                         'value' => '27'
                       }
      }
    ];
Not a HASH reference at script.pl line 43.

Why do I get this error and how can i fetch the values of temperature? 为什么会出现此错误,如何获取温度值? Thanks in advance! 提前致谢!

XML::Simple tells you not to use it. XML :: Simple告诉您不要使用它。 Follow its advice. 遵循其建议。

Here's how to extract temperature using XML::LibXML : 这是使用XML :: LibXML提取温度的方法:

#!/usr/bin/perl

use warnings;
use strict;
use feature qw{ say };

use XML::LibXML;

my $dom = 'XML::LibXML'->load_xml(
    location => 'http://www.yr.no/place/Norway/Telemark/Sauherad/Gvarv/forecast_hour_by_hour.xml');

for my $temperature ($dom->findnodes('//temperature/@value')) {
    say $temperature->getValue;
}

With xsh , which is a wrapper around XML::LibXML, you can just write 使用xsh ,它是XML :: LibXML的包装,您可以编写

open http://www.yr.no/place/Norway/Telemark/Sauherad/Gvarv/forecast_hour_by_hour.xml ;
for //temperature echo @value ;

XML::Simple is discouraged

Much easier than you think - I will suggest XML::Twig , because I think it has an easier learning curve: 比您想象的要容易得多-我建议使用XML::Twig ,因为我认为它的学习曲线更容易:

#!/usr/bin/env perl

use strict;
use warnings;

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

my $twig = XML::Twig -> parse (  get('http://www.yr.no/place/Norway/Telemark/Sauherad/Gvarv/forecast_hour_by_hour.xml') );
#print the first temperature value:
print $twig -> get_xpath('//temperature',0 ) -> att('value'),"\n";

# all the temps in an array:
use Data::Dumper;
my @temps = map { $_ -> att('value') } $twig -> get_xpath('//temperature');
print Dumper \@temps;

here we make use of an xpath search - which is a bit like a regular expression for XML. 这里我们利用xpath搜索-有点像XML的正则表达式。 // denotes "anywhere in the tree" so is effectively a search for "temperature" nodes. //表示“树中的任何位置”,因此实际上是对“温度”节点的搜索。 (Which seems to work with your XML, but you might want a more specific path in other scenarios). (这似乎可以与您的XML一起使用,但是在其他情况下,您可能需要更具体的路径)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM