Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a config file using XML::Simple?

Tags:

xml

perl

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?

like image 326
xyz Avatar asked Jun 19 '26 05:06

xyz


1 Answers

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";

Output:

text3
text8
text4
text9

You can read about KeyAttr from perldoc XML::Simple

like image 159
toolic Avatar answered Jun 21 '26 02:06

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!