How to change the order of the attributes of an XML element using Perl and XML::Twig

415 Views Asked by At

I am new to XML::Twig. I want to change the order of the attributes of all <product> elements as shown below.

Input.xml

<?xml version="1.0" encoding="utf-8"?>
<root>
  <product markup="xml" type="books" id="book1">
    <name>Analysis</name>
    <prize>$203</prize>
    <subject>Construct</subject>
  </product>
  <product markup="xml" type="books" id="book2">
    <name>Analysis</name>
    <prize>$203</prize>
    <subject>Bio</subject>
  </product>
</root>

I need like this

<?xml version="1.0" encoding="utf-8"?>
<root>
  <product id="book1" markup="xml" type="books">
    <name>Analysis</name>
    <prize>$203</prize>
    <subject>Construct</subject>
  </product>
  <product id="book2" markup="xml" type="books">
    <name>Analysis</name>
    <prize>$203</prize>
    <subject>Bio</subject>
  </product>
</root>

My code is:

use XML::Twig;

my $XML = XML::Twig->new(
  twig_handlers   => {
    #'product' => sub {$_},
    # (I don't know this process)
  },
  pretty_print    => 'record',
  output_encoding => 'utf-8',
  keep_atts_order => 1,
);

$XML->parsefile("input.xml");

$XML->purge; 

How can I change this?

1

There are 1 best solutions below

2
On

As mentioned in the comments, this is a weird request. You're probably trying to do something the wrong way ( or you are working with tools that don't really implement XML fully).

In any case, since XML::Twig by default outputs attribute in alphabetical order, and alphabetically id comes before markup, which comes before type, it looks like you don't have to do anything. Remove the keep_atts_order option, read and write the file, voilà! I suspect most other XML tools will behave this way too.