2

Perl snippet:

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

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

Configfile looks like:

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

How do I parse this config file so that c becomes a key and I can access the corresponding b and d? What does KeyAttr do?

toolic
  • 57,801
  • 17
  • 75
  • 117
xyz
  • 8,607
  • 16
  • 66
  • 90

1 Answers1

3

XML::Simple returns a Perl data structure (see perldoc perldsc) which you can visualize using Data::Dumper. Here is one way to access the data you need:

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

You can read about KeyAttr from perldoc XML::Simple

toolic
  • 57,801
  • 17
  • 75
  • 117
  • Thanks for the pointer perldoc XML::Simple . Explains the usage KeyAttr => {a => b}. Many tutorials only explain KeyAttr=>a usage. – xyz Jan 28 '12 at 15:12