in reply to Predefining complex data structures?

first, i would change the data structure to:

$tagstack{requirements}->[1] = { text => "A node name", attributes => {contactname => "Jane Smith", contactnumber => "555-1212" } }

note that it is not a hash containing a reference to an array which contains hashrefs. also note the curly braces around the attributes hash instead of square braces.

if XML::Simple is up to the task of parsing your XML, this is fairly straightforward. here's a little script showing how you would go about it:

#!/usr/bin/perl -wT use strict; use XML::Simple; use Data::Dumper; my $data = XML::Simple::XMLin('./test.xml'); # show what we start with print Data::Dumper::Dumper($data); my %tagstack; my @temp; foreach my $h (@{$data->{requirement}}) { my %t; $t{text} = $h->{content}; delete $h->{content}; $t{attributes} = $h; push @temp, \%t; } $tagstack{requirement} = \@temp; # show the finished product print Data::Dumper::Dumper(\%tagstack);

with test.xml being:

<root> <requirement contactname="Joe Average">A power cord.</requirement> <requirement contactname="Jane Smith" contactnumber="555-1212">A node +name</requirement> </root>

it gives the following output:

$VAR1 = { 'requirement' => [ { 'contactname' => 'Joe Average', 'content' => 'A power cord.' }, { 'contactnumber' => '555-1212', 'contactname' => 'Jane Smith', 'content' => 'A node name' } ] }; $VAR1 = { 'requirement' => [ { 'text' => 'A power cord.', 'attributes' => { 'contactname' => 'Joe + Average' } }, { 'text' => 'A node name', 'attributes' => { 'contactnumber' => '5 +55-1212', 'contactname' => 'Jan +e Smith' } } ] };

personally, i think the data structure that XML::Simple produces is more intuitive, but you've probably got a reason for wanting it in the format you do.

anders pearson

Replies are listed 'Best First'.
Re: Predefining complex data structures?
by Ionizor (Pilgrim) on Jul 12, 2002 at 16:32 UTC

    Okay, I've looked over the changes you suggested to the data structure. The only thing I wasn't quite clear on was what the -> arrow operator at the beginning does. I haven't seen it used in that particular way in Perl before. Admittedly I'm still less than 200 pages into the Camel book.

    Unfortunately though it is more intuitive, XML::Simple isn't quite enough to do what I need to do as it would be more complicated to reassemble the data in the <method> structure I provided in another part of this thread than it would be to just stick with XML::Parser. With XML::Parser I can use an if or a case to fire off different code for an <object> or <input> element so that I can apply formatting (that's all the object and input tags are for) without have to reassemble the strings.

    Thanks!