2012-01-28 70 views
2

我有一個Perl代碼段爲:如何在Perl中使用XML :: Simple解析配置文件?

my $xml = new XML::Simple(
    KeyAttr=>{ 
     property => 'propertyname',   
    }, 
    ForceArray => 1, 
    ContentKey => '-content'); 

my $config = $xml->XMLin($configFile); 

CONFIGFILE樣子:

<config> 
<property propertyname="text1" b="text2" c="text3" d="text4"> 
text5 
</property> 
<property propertyname="text6" b="text7" c="text8" d="text9"> 
text10 
</property> 
</config> 

我新的Perl和XML ::簡單。如何解析這個配置文件,使c成爲關鍵,我可以訪問相應的b,d。 KeyAttr上面告訴了什麼?

回答

3

XML :: Simple返回一個Perl數據結構(請參閱perldoc perldsc),您可以使用Data::Dumper將其可視化。 這裏訪問你需要的數據的一種方法:

use warnings; 
use strict; 
use XML::Simple; 

my $xfile = ' 
<config> 
<property propertyname="text1" b="text2" c="text3" d="text4"> 
text5 
</property> 
<property propertyname="text6" b="text7" c="text8" d="text9"> 
text10 
</property> 
</config> 
'; 

my $xml = new XML::Simple(
    KeyAttr=>{ 
     property => 'propertyname',   
    }, 
    ForceArray => 1, 
    ContentKey => '-content'); 

my $config = $xml->XMLin($xfile); 

print "$config->{property}{text1}{c}\n"; 
print "$config->{property}{text6}{c}\n"; 
print "$config->{property}{text1}{d}\n"; 
print "$config->{property}{text6}{d}\n"; 

__END__ 

text3 
text8 
text4 
text9 

你可以閱讀有關KeyAttrperldoc XML::Simple

+0

感謝指針的perldoc XML ::簡單。解釋用法KeyAttr => {a => b}。許多教程僅解釋KeyAttr =>用法。 – xyz 2012-01-28 15:12:07