in reply to Swapping XML Elements

To emphasise and make a little clearer what previous replies have said: It is almost never appropriate to use a regex to manipulate XML. The two biggest problems are whitespace and nested elements. It is very hard, and in many cases not possible in any sensible way, to write regexen to perform edits on XML.

As mentioned by marto, XML::Twig is the way to do this sort of thing:

use strict; use warnings; use XML::Twig; my $t= XML::Twig->new ( twig_roots => {'figure' => \&doSwap}, twig_print_outside_roots => 1, ); my $source = do {local $/ = ''; <DATA>}; $t->set_pretty_print ('record'); $t->parse ($source); sub doSwap { my ($t, $figure)= @_; my @title = $figure->cut_children ('title'); $title[0]->paste ('last_child', $figure); $figure->print; }
__DATA__ <root> <figure airframe="PLATFORM-1" id="aircraftupdimensions" span="1" tocen +try="1"> <title>Aircraft Up Dimensions</title> <graphic fileref="MH60S_Figures\Chapter_1\aircraftupdimensions.jpg" /> </figure> <figure airframe="PLATFORM-1" id="aircraftupclearanceandturningradius" + span="1"> <title>Aircraft Up Clearance and Turning Radius</title> <graphic fileref="MH60S_Figures\Chapter_1\aircraftupclearanceandturnin +gradius.jpg" /> </figure> <para airframe="PLATFORM-1"></para> <figure airframe="PLATFORM-1" id="aircraftdownclearanceandturningradiu +s" span="1"> <title>Aircraft Down Clearance and Turning Radius</title> <graphic fileref="MH60S_Figures\Chapter_1\aircraftdownclearanceandturn +ingradius.jpg" /> </figure> <figure airframe="PLATFORM-1" id="aircraftdowndimensions" span="1" toc +entry="1"> <title>Aircraft Down Dimensions</title> <graphic fileref="MH60S_Figures\Chapter_1\aircraftdowndimensions.jpg" +/> </figure> </root>

Prints:

<root> <figure airframe="PLATFORM-1" id="aircraftupdimensions" span="1" toc +entry="1"> <graphic fileref="MH60S_Figures\Chapter_1\aircraftupdimensions.jpg +"/> <title>Aircraft Up Dimensions</title> </figure> <figure airframe="PLATFORM-1" id="aircraftupclearanceandturningradiu +s" span="1"> <graphic fileref="MH60S_Figures\Chapter_1\aircraftupclearanceandtu +rningradius.jpg"/> <title>Aircraft Up Clearance and Turning Radius</title> </figure> <para airframe="PLATFORM-1"></para> <figure airframe="PLATFORM-1" id="aircraftdownclearanceandturningrad +ius" span="1"> <graphic fileref="MH60S_Figures\Chapter_1\aircraftdownclearanceand +turningradius.jpg"/> <title>Aircraft Down Clearance and Turning Radius</title> </figure> <figure airframe="PLATFORM-1" id="aircraftdowndimensions" span="1" t +ocentry="1"> <graphic fileref="MH60S_Figures\Chapter_1\aircraftdowndimensions.j +pg"/> <title>Aircraft Down Dimensions</title> </figure> </root>

DWIM is Perl's answer to Gödel