如何从XML :: Simple的数据结构中提取值?

问题描述:

我想弄清楚如何解析XML中前2个(37%61.8F)中的<current></current>值。因为他们似乎有相同的字段名和都在“传感器” ...任何帮助,将不胜感激在Perl我不出来...如何从XML :: Simple的数据结构中提取值?

代码:

#!/usr/bin/perl 

use XML::Simple; 
use Data::Dumper; 
use LWP::Simple; 


$url = 'http://localhostmachine/output/XML/output.xml'; 

# create object 
my $xml = XML::Simple->new(); 

# read XML file 
$data = $xml->XMLin(get($url)); 

# print output 
print Dumper($data); 

我正在阅读的XML文件的输出:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<?xml-stylesheet type="text/xsl" href="wpman.xsl"?> 
<watchport> 
<title> 
<TxtTitle>Location#1</TxtTitle> 
</title> 
<sensor> 
<type>Combo Sensor (Humidity)</type> 
<name>ComboSensor000</name> 
<status>OK</status> 
<current>37%</current> 
<high>42 (10/19/2009 @ 04:05PM)</high> 
<low>28 (10/17/2009 @ 11:26AM)</low> 
</sensor> 
<sensor> 
<type>Combo Sensor (Temperature)</type> 
<name>ComboSensor000</name> 
<status>OK</status> 
<current>61.6F</current> 
<high>65.8 (10/17/2009 @ 11:26AM)</high> 
<low>60.1 (10/19/2009 @ 04:00PM)</low> 
</sensor> 
<sensor> 
<type> </type> 
<name> </name> 
<status> </status> 
<current> </current> 
</sensor> 
<sensor> 
<type>Updated: 10/19/2009 @ 05:47 PM</type> 
<name>(Updated every 2 minutes)</name> 
<status> </status> 
<current> </current> 
</sensor> 
</watchport> 

非常感谢!

+0

我的错误,我的意思是这是输入XML。抱歉! – 2009-10-19 22:38:06

+1

@Josh G.请在脚本中使用strict;'和'warnings;'。 – 2009-10-19 23:25:16

我认为这是你想要的。

print $data->{sensor}[0]{current}; 
print $data->{sensor}[1]{current}; 
+0

omg,就这么简单!?我正在尝试$ data - > {sensor [0]} 非常感谢Tim! – 2009-10-19 22:51:17

既然你已经得到了答案,这里有一些你可能会发现有用的链接。

他们给出了一个很好的介绍使用引用和复杂的数据结构,以及大量的例子。

我并不想轻视地向你扔掉RTFM,请不要以我的方式回应。 Perl有很多文档,在开始时很难找到解决问题的方法。 How to RTFM是一个很好的资源,可以帮助揭开手册的神秘面纱。

+0

+1。我可以再投票! ;-) – 2009-10-20 00:55:48