I have already seen several answers in different places regarding setting the order of returned XML elements XMLout. However, I cannot solve the problem using these answers / examples.
I have a script that should output some XML data, and some elements should be printed in a specific order. The hash is quite complex, and I could not achieve any results by overriding it sorted_keysinto XML::Simplean object. Well, I did, but not the way I wanted.
The code example is below, detailed information about the problem is given below the code.
use strict;
use warnings;
use XML::Simple;
package MyXMLSimple;
use base 'XML::Simple';
sub sorted_keys
{
my ($self, $name, $hashref) = @_;
return $self->SUPER::sorted_keys($name, $hashref);
}
package main;
my $xmlParser = MyXMLSimple->new;
my $items = {
'status' => 'OK',
'fields' => {
'i1' => {
'header' => 'Header 1',
'max_size' => '3'
},
'i2' => {
'header' => 'Header 2',
'max_size' => '8'
}
},
'item_list' => {
'GGG' => {
'index' => '3',
'i' => 3,
'points' => {
'p5' => {
'data' => '10',
}
},
},
'AAA' => {
'index' => '1',
'i' => 2,
'points' => {
'p7' => {
'data' => '22',
}
},
},
'ZZZ' => {
'index' => '2',
'i' => 1,
'points' => {
'p6' => {
'data' => '15',
}
},
}
}
};
my $xml = $xmlParser->XMLout($items);
print "$xml";
So, the output of this script will be as follows:
<opt status="OK">
<fields name="i1" header="Header 1" max_size="3" />
<fields name="i2" header="Header 2" max_size="8" />
<item_list name="AAA" i="2" index="1">
<points name="p7" data="22" />
</item_list>
<item_list name="GGG" i="3" index="3">
<points name="p5" data="10" />
</item_list>
<item_list name="ZZZ" i="1" index="2">
<points name="p6" data="15" />
</item_list>
</opt>
item_listelements are printed, and the output order is in alphabetical order by sorting by attribute name. The output order is AAA, GGG, ZZZ.
, ( , ) i. , ZZZ, AAA, GGG.
( Tie::...), . NoSort => 1, , .
, , , , sorted_keys. , , sorted_keys item_list. sorted_keys opt, -, Tie::.
, , Tie::IxHash, sorted_keys (re), item_list, ( ), .
- :
sub sorted_keys
{
my ($self, $name, $hashref) = @_;
if ($name eq "opt")
{
my $clist = { };
tie %{$clist}, "Tie::IxHash";
my @sorted_keys = sort { $hashref->{item_list}->{$a}->{i} <=> $hashref->{item_list}->{$b}->{i} } keys %{$hashref->{item_list}};
foreach my $sorted_key (@sorted_keys)
{
$clist->{$sorted_key} = $hashref->{item_list}->{$sorted_key};
}
delete $hashref->{item_list};
$hashref->{item_list} = $clist;
}
return $self->SUPER::sorted_keys($name, $hashref);
}
, ( , , ), , , Tie::IxHash , -/, / sorted_keys.
, , sorted_keys ( / ;), , -, .
, XML/Simple.pm sorted_keys, - . , , , name, i.
:)