Search code examples
xmlperlxml-simple

How do I disable subtag sorting in Perl's XML::Simple?


I just want to find the way of disable the sort operation in XML::Simple

For example:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Simple;

my %my_xml = (
    NAME  => [ 'test' ],
    EMAIL => [ '[email protected]' ],
    ID    => 12,
);

my $xs = XML::Simple->new;
print $xs->XMLout(\%my_xml, RootName => "datas", NoSort => 1);

__END__

I get following output:

<datas ID="12">
  <EMAIL>[email protected]</EMAIL>
  <NAME>test</NAME>
</datas>

But I want the output to be:

<datas ID="12">
  <NAME>test</NAME>
  <EMAIL>[email protected]</EMAIL>
</datas>

How can I achieve this?


Solution

  • According the Grant McLean (author of XML::Simple)

    if we want is for the order of elements from the original document to be retained. Unfortunately, that is not possible with XML::Simple. When the document is parsed, XML::Simple stores the element data in hashes. Hashes do not remember the order in which keys were added so this data is lost.

    If we want to retain the document order you need to use a different module. he recommends XML::LibXML. In fact he wrote an article about switching from XML::Simple to XML::LibXML here:

    http://www.perlmonks.org/index.pl?node_id=490846