I'm using XML::Twig to manipulate my xml data and it's working fine. But I get new requirement to order my xml records. I doubt whether XML::Twig can find the correct position to add record so the data is properly ordered by "name" alphabetically OR I must add it in random position and sort it then.
This is the further coding for my last script at http://www.perlmonks.org/index.pl?node_id=719528, Thank you Tanktalus to help revise my coding.
and the xml file is here:#!/usr/bin/perl -w use strict; use XML::Twig; my %links = ( "img" => "/images/Orange_Test.jpg", "alt" => "Orange Test Image", "name" => "Orange Test Image", "title" => "Hello World. This is a test page. Please clic +k here for more information.", "url" => "http://localhost/orange_test.htm", "dcr" => "/templatedata/test2123/test/orange_test", ); my $path = "/orange_test.htm"; my $file = "s1.xml"; my $x = XML::Twig::Elt->new( record => map { XML::Twig::Elt->new( $_ => $links{$_}) } sort keys %links) ->set_att("path",$path); my $twig = XML::Twig->new(pretty_print => 'indented'); if(!-s $file) { $twig->set_root( XML::Twig::Elt->new(data => $x) ); } else { my $item_pasted; $twig->setTwigHandlers( { record => sub { my( $twig, $record)= @_; unless ($item_pasted) { my $rpath = $record->att('path' +); if ($rpath eq $path) { $x->replace($record); $item_pasted=1; return } } }, } ); $twig->parsefile($file); $x->paste('last_child',$twig->root) unless($item_pasted); } { open (my $xfile, ">", $file) or die "Can't save to $file: $!"; $twig->print(\*$xfile); }
Thank you in advance.<data> <record path="/blue_test.htm"> <alt>Blue Test</alt> <dcr>/templatedata/test2123/test/blue_test</dcr> <img>/images/Blue_Test.jpg</img> <name>Blue Test</name> <title>Hello World. This is a test page. Please click here for mor +e information.</title> <url>http://localhost/blue_test.htm</url> </record> <record path="/yellow_test.htm"> <alt>Yellow Test</alt> <dcr>/templatedata/test2123/test/yellow_test</dcr> <img>/images/Yellow_Test.jpg</img> <name>Yellow Test</name> <title>Hello World. This is a test page. Please click here for mor +e information.</title> <url>http://localhost/yellow_test.htm</url> </record> </data>
In reply to use XML::Twig to insert data in the correct order by sureerat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |