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

Hello Monks,

I want to set parent tag for some successive tags.

My xml file:-

<root> <one>some text</one> <two>some text</two> <three>some text</three> .... .... </root>

I want parent tag for tags <two> and <three> output as

<root> <one>some text</one> <group> <two>some text</two> <three>some text</three> </group> .... .... </root>

I tried with get_xpath. But I can't get grouping the specified successive tags.

thanks,

Replies are listed 'Best First'.
Re: set parent for some successive elements using XML::Twig
by GrandFather (Saint) on Apr 27, 2007 at 12:04 UTC

    The following should get you started. Note that there is a lack of error checking in the sample code!

    use strict; use warnings; use XML::Twig; my $content = do {local $/; <DATA>}; my $twig = XML::Twig->new(pretty_print => 'nice'); $twig->parse($content); my @first = $twig->get_xpath('//one'); my @elts = $twig->get_xpath('//two'); push @elts, $twig->get_xpath('//three'); my $group = XML::Twig::Elt->new ('group'); $group->paste ('after', $first[0]); $_->move ('last_child', $group) for @elts; $content = $twig->sprint; print $content; __DATA__ <root> <one>some text</one> <two>some text</two> <three>some text</three> <four>more text</four> </root>

    Prints:

    <root> <one>some text</one> <group> <two>some text</two> <three>some text</three> </group> <four>more text</four> </root>

    DWIM is Perl's answer to Gödel