pop18 has asked for the wisdom of the Perl Monks concerning the following question:

I'm a kid to perl striving to learn perl. please help me out with this
How to replace a block of XML tag like
<abc>This is ....</abc>
<abc>sddfd....</abc>
with
<xyz>
<abc>This is ....</abc>
<abc>sddfd....</abc>
</xyz>
Thanx in advance
POP18

Replies are listed 'Best First'.
Re: XML tag replace
by GrandFather (Saint) on Jul 13, 2007 at 10:17 UTC

    Either the answer is trivial:

    use warnings; use strict; print "<xyz>\n"; print <DATA>; print "</xyz>\n"; __DATA__ <abc>This is ....</abc> <abc>sddfd....</abc>

    or there is a bunch of information missing from your question.

    When you supply the missing information (I'm pretty sure you're not looking for the trivial answer) you would do well to show what you have tried so far.

    You may find either XML::Twig or XML::TreeBuilder of some help in generating a solution to your problem.


    DWIM is Perl's answer to Gödel
      Apology for the message. I want to make the number of lines short considering server space. Let me explain it in detail.
      I have the code like this

      <author-group> <auth> </auth> <auth> </auth> <auth> </auth> <aff> </aff> <aff> </aff> <corres id="cor1"> </corres> </author-group>

      I want to group all <auth> tags in a separate tag like

      <author-group> <XXX> <auth> </auth> <auth> </auth> <auth> </auth> <XXX> <aff> </aff> <aff> </aff> <corres id="cor1"> </corres> </author-group>

      I tried this using regular expression. I can’t get the “</auth>carriage return <aff>”. Please advice.

      Could you please suggest any book to learn basics of perl.

      Edit: g0n - code tags

        Learning Perl would be a good book to start with. You may find that the monastery's Tutorials section is good for a quick start.

        Here's a starting point for your XML manipulation using XML::TreeBuilder:

        use strict; use warnings; use XML::TreeBuilder; my $xml = <<XML; <author-group> <auth> </auth> <auth> </auth> <auth> </auth> <aff> </aff> <aff> </aff> <corres id="cor1"> </corres> </author-group> XML my $root = XML::TreeBuilder->new (); $root->parse ($xml); for my $group ($root->look_down ('_tag', 'author-group')) { my @auths = $group->look_down ('_tag', 'auth'); my $newRoot = HTML::Element->new ('xxx'); $_->detach () for @auths; $newRoot->push_content (@auths); $group->unshift_content ($newRoot); } print $root->as_XML ();

        Prints:

        <author-group><xxx><auth> </auth><auth> </auth><auth> </auth></xxx> <aff> </aff> <aff> </aff> <corres id="cor1"> </corres> </author-group>

        Still pretty trivial eh.;)


        DWIM is Perl's answer to Gödel
        As far as learning Perl basics goes, "Learning Perl", published by O'Reilly & Associates, is excellent. I bought it years ago, and I still refer to it.