Wednesday, 11 June 2014

Read in and out from a XML file

This is a simple program I knew today can help us to read and print values from a XML file.

It's a sample file called foo.xml:

  <config logdir="/var/log/foo/" debugfile="/tmp/foo.debug">
    <server name="sahara" osname="solaris" osversion="2.6">
      <address>10.0.0.101</address>
      <address>10.0.1.101</address>
    </server>
    <server name="gobi" osname="irix" osversion="6.5">
      <address>10.0.0.102</address>
    </server>
    <server name="kalahari" osname="linux" osversion="2.0.34">
      <address>10.0.0.103</address>
      <address>10.0.1.103</address>
    </server>
  </config>

save it to the same directory of the perl program.

 It's the perl program called foo.pl:

  use XML::Simple qw(:strict);

  my $config = XMLin('foo.xml', KeyAttr => { server => 'name' }, ForceArray => [ 'server', 'address' ]);
 
 use Data::Dumper;

 print Dumper($config);

 print "$config->{logdir}\n";

#You can assign the field to a variable in your perl program, very handy.
 $a = "$config->{server}->{kalahari}->{address}->[1]";
 print "$a";


It produces the following:

C:\Users\Administrator\Desktop\practice material\perl>foo.pl
$VAR1 = {
          'debugfile' => '/tmp/foo.debug',
          'server' => {
                      'kalahari' => {
                                    'osversion' => '2.0.34',
                                    'osname' => 'linux',
                                    'address' => [
                                                 '10.0.0.103',
                                                 '10.0.1.103'
                                               ]
                                  },
                      'sahara' => {
                                  'osversion' => '2.6',
                                  'osname' => 'solaris',
                                  'address' => [
                                               '10.0.0.101',
                                               '10.0.1.101'
                                             ]
                                },
                      'gobi' => {
                                'osversion' => '6.5',
                                'osname' => 'irix',
                                'address' => [
                                             '10.0.0.102'
                                           ]
                              }
                    },
          'logdir' => '/var/log/foo/'
        };
/var/log/foo/
10.0.1.103

No comments:

Post a Comment