XML :: Twig and preserve the order of attributes

I am editing some XML files using XML::Twig

below:

my $twig = XML::Twig->new(
    pretty_print  => 'indented',
    twig_handlers => {
        Vendor => sub {
            $_->set_att( 'ID' => $_->{'att'}->{'att1'} );
            $_->set_att( 'ID' => $_->{'att'}->{'att2'} );
            $_->set_att( 'ID' => $_->{'att'}->{'att3'} );
            $_->set_att( 'ID' => $_->{'att'}->{'att4'} );
        },
    },
);

$twig->parsefile('myfile');
$twig->flush;

      

The problem is that this code does not store the xml attributes in the same order in the edited file.

for example this line from xml input:

<DEVICE OVERWRITE="TRUE" STRING="TRUE" BLOCK="FALSE">

      

is replaced with this line in the xml output:

<DEVICE  BLOCK="FALSE" STRING="TRUE"  OVERWRITE="TRUE">

      

How do I keep the attributes in the same order as the original file so that if I compare the two files with the revision system, I only see the changes I made?

+3


source to share


1 answer


Are you sure that the order BLOCK

, STRING

, OVERWRITE

? It would be a little surprising.

To answer your question: try setting Tie::IxHash

and using the parameter keep_atts-order

when creating a branch. This should do it.



I'm not sure why you need this: the order shouldn't matter to any (correct) XML processor. If you need this for version control, you can look at the value cvs

for the parameter pretty_print

, which is for playing with line-oriented tools.

+4


source







All Articles