Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: XMLout and Elements vs Attributes

by dasgar (Curate)
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.


Comment on Re: XMLout and Elements vs Attributes
Select or Download Code
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.

    cheers!

    EDIT

    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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1075607]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (11)
As of 2015-07-07 07:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (87 votes), past polls