use strict; use warnings; # creating my object with a sortorder my $xs = new MyXMLSimple( XMLDecl => '', KeepRoot => 1, KeyAttr => [ ], SortOrder => { supertag => [qw[ tag1 tag3 tag4 tag10 ]], }, ); # Some testdata my $structure = { supertag => { tag10 => { content => 'value 2', }, tag3 => { content => 'value 3', }, tag1 => { content => 'value 1', }, tag91 => { content => 'value 91', }, tag90 => { content => 'value 90', }, tag4 => { content => 'value 4', }, } }; print $xs->XMLout($structure); ################################################################################ package MyXMLSimple; # my XML::Simple subclass use base 'XML::Simple'; use Carp; sub new { my $class= shift; if(@_ % 2) { croak "Default options must be name=>value pairs (odd number supplied)"; } my %raw_opt = @_; # removing my new option from the options supplied my $sortorder= delete $raw_opt{'SortOrder'}; # creating the XML::Simple element my $self= $class->SUPER::new( %raw_opt ); # adding the sortorder in $self->{'SortOrder'}= $sortorder; return (bless($self, $class)); } # Overriding the method here sub sorted_keys { my ($self, $name, $hashref) = @_; # check whether we have a sortorder for $name my $ordered= $self->{'SortOrder'}->{$name}; if ($ordered) { # if so, prepare the sortorder my %ordered_hash; @ordered_hash{@$ordered} = (); #set ordered tags in front of others return grep {exists $hashref->{$_}} @$ordered, grep {not exists $ordered_hash{$_}} $self->SUPER::sorted_keys($name, $hashref); } return $self->SUPER::sorted_keys($name, $hashref); # for the rest, I don't care! }