Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: XMLout and Elements vs Attributes

by dasgar (Priest)
on Feb 20, 2014 at 16:56 UTC ( #1075607=note: print w/replies, xml ) Need Help??

in reply to XMLout and Elements vs Attributes

The documentation of XML::Simple shows you exactly how to do this. (see the Quick Start section)

Here's how I changed your code:

#!/usr/bin/perl use strict; use warnings FATAL => 'uninitialized'; use XML::Simple qw(:strict); use Data::Dumper; $| = 1; my %ref; # create 1st node push(@{$ref{'node'}},{ 'id' => 'net_1.2.3.0', 'desc' => ['network'], }); # create 2nd node push(@{$ref{'node'}},{ 'id' => 'ip_1.2.3.4', 'desc' => ['ipaddr'], }); my $xmlParser = XML::Simple->new(); my $fh;open $fh,'>','testfile.xml' or die "$!"; $xmlParser->XMLout(\%ref,( 'XMLDecl' => '<?xml version="1.0" encoding="utf-8"?>', 'NoAttr' => 0, 'KeepRoot' => 0, 'RootName' => 'test', 'OutputFile' => $fh, 'AttrIndent' => 1, 'KeyAttr' => { 'node' => 'id' }, )); print Dumper \%ref;

Here's the script output:

$VAR1 = { 'node' => [ { 'desc' => [ 'network' ], 'id' => 'net_1.2.3.0' }, { 'desc' => [ 'ipaddr' ], 'id' => 'ip_1.2.3.4' } ] };

Here's the XML file that was created:

<?xml version="1.0" encoding="utf-8"?> <test> <node id="net_1.2.3.0"> <desc>network</desc> </node> <node id="ip_1.2.3.4"> <desc>ipaddr</desc> </node> </test>

Basically, I just changed the 'desc' element from being a hash to be a hash of an array instead.

Replies are listed 'Best First'.
Re^2: XMLout and Elements vs Attributes
by atreyu (Sexton) on Feb 20, 2014 at 17:00 UTC
    Thanks, dasgar (and jellisii2), that's what I came up with too. So I guess that is *the way* to do it.



    yep, you're right, dasgar. i (thought i) had read the entire documentation, but my eyes glossed right over the example in the Quick Start area. d'oh.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1075607]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2018-05-21 05:35 GMT
Find Nodes?
    Voting Booth?