XML::Twig and save order of attributes
Asked Answered
S

2

7

I am editing some XML files using XML::Twig below are the code :

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 save the xml attributes in the same order in the edited file.

for example this line from the input xml :

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

is replaced by this line in the output xml :

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

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

Siamese answered 22/10, 2014 at 15:56 Comment(0)
D
6

Are you sure the order is BLOCK, STRING, OVERWRITE? This would be a bit surprising.

To answer your question: try installing Tie::IxHash and using the keep_atts_order option when you create the twig. This should do it.

I am not sure why you would need this though: the order shouldn't matter for any (proper) XML processor. If you need this for version control, you could have a look at the cvs value for the pretty_print option, which is designed to play nice with line-oriented tools.

Darmit answered 22/10, 2014 at 16:19 Comment(0)
B
2

If it saves people having to search like I did to figure out the syntax to get it working... after reading the source of XML::Twig I successfully implemented mirod's suggestion with:

use Tie::IxHash;
$twig->set_keep_atts_order(1);

Tie::IxHash turned out to already be installed on my box, so that was easy!

Bubal answered 15/12, 2020 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.