Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: XMLout and Elements vs Attributes

by dasgar (Priest)
on Feb 20, 2014 at 16:56 UTC ( [id://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.

    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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1075607]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2024-04-18 12:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found