Reputation: 23
I am trying to add an attribute to existing XML, using XML::Simple.
<arbre>
<branche name="courbe" >
<description>
<![CDATA[une belle branche]]>
</description>
<feuilles>
<fleur color="blue" order="1" />
<fleur color="white" order="2" />
<fleur color="yellow" order="3" />
</feuilles>
</branche>
<branche name="droite" >
<description>
<![CDATA[une branche commune]]>
</description>
<feuilles>
<fleur color="purple" order="1" />
<fleur color="green" order="2" />
</feuilles>
</branche>
</arbre>
That I am trying to transform into :
<arbre>
<branche name="courbe" type="conifere">
<description>
<![CDATA[une belle branche]]>
</description>
<feuilles>
<fleur color="blue" order="1" />
<fleur color="white" order="2" />
<fleur color="yellow" order="3" />
</feuilles>
</branche>
<branche name="droite" type="resineux">
<description>
<![CDATA[une branche commune]]>
</description>
<feuilles>
<fleur color="purple" order="1" />
<fleur color="green" order="2" />
</feuilles>
</branche>
</arbre>
Notice the type attribute in branche tag.
So far I have the following :
#!/usr/bin/env perl -w
use strict;
use XML::Simple;
use Data::Dumper;
my $funclist = XML::Simple->new();
my $arbres = $funclist->XMLin("test.xml");
print Dumper($arbres);
exit 0;
From what I understand from the documentation $arbres is a hash in which I have to insert in each branche key the type attribute key and value.
Exept that I have no clue at where and how ($arbres{something} = "conifere" ?).
Thanks
Upvotes: 2
Views: 1128
Reputation: 39158
use strict;
use warnings FATAL => 'all';
use XML::Simple qw();
my %branche_map = (
courbe => 'conifere',
droite => 'resineux',
);
my $xs = XML::Simple->new(StrictMode => 1, ForceArray => 1, KeyAttr => undef, RootName => 'arbre');
my $arbres = $xs->XMLin('test.xml');
for my $branche (@{ $arbres->{branche} }) {
$branche->{type} = $branche_map{ $branche->{name} };
}
print $xs->XMLout($arbres)
Upvotes: 3
Reputation: 241748
Using XML::XSH2, a wrapper around XML::LibXML
open test.xml ;
for //branche[@name='courbe'] set @type 'conifere' ;
for //branche[@name='droite'] set @type 'resineux' ;
save :b ;
Upvotes: 2