xml version="1.0" encoding="UTF-8"?>
<employees>
<employee age = "30">
<name>linuxname>
<country>UScountry>
employee>
<employee age = "10">
<name>macname>
<country>UScountry>
employee>
<employee age = "20">
<name>windowsname>
<country>UScountry>
employee>
employees>
use File::Basename;
use XML::Simple;
use Data::Dumper;
my $xmlfile = dirname($0) . "\\employees.xml";
if (-e $xmlfile)
{
print "-----------------------------------------\n";
my $userxs = XML::Simple->new(KeyAttr => "name");
my $userxml = $userxs->XMLin($xmlfile);
# print output
print Dumper($userxml);
my %allemployees = %{$userxml->{employee}};
foreach my $key (keys(%allemployees))
{
print $key . " ";
print $allemployees{$key}{"age"} . "\n";
}
print "-----------------------------------------\n";
my $userxsT = XML::Simple->new(ForceArray => 1);
my $userxmlT = $userxsT->XMLin($xmlfile);
# print output
print Dumper($userxmlT);
my @allemployeeT = @{$userxmlT->{"employee"}};
foreach my $employee (@allemployeeT)
{
print $employee->{"name"}[0] . " ";
print $employee->{"age"} . "\n";
}
}
use File::Basename;
use XML::Simple;
use Data::Dumper;
print "-----------------------------------------\n";
# create array
my @arr = [
{'country'=>'england', 'capital'=>'london'},
{'country'=>'norway', 'capital'=>'oslo'},
{'country'=>'india', 'capital'=>'new delhi'} ];
# create object
my $xml = new XML::Simple(NoAttr=>1, RootName=>'dataroot');
# convert Perl array ref into XML document
my $data = $xml->XMLout(\@arr,outputfile => "output1.xml");
print "-----------------------------------------\n";
my $str=<<_XML_STRING_;
<config logdir="/var/log/foo/" debugfile="/tmp/foo.debug">
<server name="sahara" osname="solaris" osversion="2.6">
<address>10.0.0.101address>
<address>10.0.1.101address>
server>
<server name="gobi" osname="irix" osversion="6.5">
<address>10.0.0.102address>
server>
<server name="kalahari" osname="linux" osversion="2.0.34">
<address>10.0.0.103address>
<address>10.0.1.103address>
server>
config>
_XML_STRING_
my $xml_ref=XMLin($str,KeepRoot => 1);
my $xml_str=XMLout($xml_ref,outputfile => "output2.xml");
print "-----------------------------------------\n";