Well, while XML::Twig tries real hard to do what you want, it still doesn't understand that line:

$twig->get_xpath('//source')->move('before', $twig->get_xpath('//pagesource'));

You have to pay attention to what the methods return: here get_xpath returns a list of XML::Twig::Elt. When you try to apply an XML::Twig method to that (unblessed) array... you get the error message you reported. You have to loop over the elements of that array yourself, and move them one by one. Bummer, I know ;--)

Here is my take on this:

#!/usr/bin/perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig->new(pretty_print => 'nice'); $twig->parse(\*DATA); foreach my $elt ($twig->get_xpath('//source')) { $elt->move( before => $elt->prev_sibling( 'pagesource')); } $twig->print; # use print_to_file to print to a file __DATA__ <root> <pagesource> <para>Teacher's Guide Level A</para><para><graphic alt="title" links=" +Studio Logo R BW.tif"/></para> </pagesource> <source> <paragraph>ISBN-13: 978-1-4190-4181-5</paragraph><paragraph>ISBN-10: 1 +-4190-4181-9</paragraph> </source> <pagesource> <para>Teacher's Guide Level A</para><para><graphic alt="title" links=" +Studio Logo R BW.tif"/></para> </pagesource> <source> <paragraph>ISBN-13: 978-1-4190-4181-5</paragraph><paragraph>ISBN-10: 1 +-4190-4181-9</paragraph> </source> </root>

In reply to Re: Swaping xml elements using XML::Twig by mirod
in thread Swaping xml elements using XML::Twig by aakikce

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.