The simplest answer is "don't do that". If you want elements output in a particular order then they should be in an arrayref in your data structure rather than a hashref, e.g.:
CPAN::Forum
XML-Simple - Re: XML::Simple Sorting
| Posted on Thu Nov 22 00:17:56 2007 by grantm in response to 6493 (See the whole thread of 3) |
| Re: XML::Simple Sorting |
|
The simplest answer is "don't do that". If you want elements output in a particular order then they should be in an arrayref in your data structure rather than a hashref, e.g.:
my $hashref = {
item => [
{ id => 1, label => 'foo' },
{ id => 2, label => 'bar' },
{ id => 11, label => 'baz' },
]
};
Another approach would be leave your data structure as it is but override XML::Simple's 'hash_to_array' method, e.g.:
#!/usr/bin/perl
use strict;
use warnings;
my $hashref = {
item => {
"2" => { label => 'bar' },
"1" => { label => 'foo' },
"11" => { label => 'baz' }
}
};
my $xs = XML::SortedSimple->new();
my $xml = $xs->XMLout( $hashref, KeyAttr => ['id'] );
print $xml;
package XML::SortedSimple;
use base 'XML::Simple';
sub hash_to_array {
my $self = shift;
my $ref = $self->SUPER::hash_to_array(@_);
if( UNIVERSAL::isa($ref, 'ARRAY') ) {
$ref = [ sort { $a->{id} || 0 <=> $b->{id} || 0 } @$ref ];
}
return $ref;
}
In this example, any hashref that does get unfolded into an arrayref will have its elements sorted (numerically) by the value of the id keys. Probably best to go with massaging your data structure though. |
| Direct Responses: 6495 | Write a response |
(14)
]