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

Hi everyone, I'm new here, and I'm trying to teach myself XML::Twig for a project at work. I'm having a bit of trouble with the paste() method though--it seems to paste an element 1.5 times. Here's what I mean:
my $root = XML::Twig::Elt->new('root'); my $tag = 'tag'; my $content = 'content'; my $next = XML::Twig::Elt->new($tag, $content); $next->paste('last_child', $root); my $element = $root; while($element = $element->next_elt() ) { $element->print; print "\n"; }
The output of this is:
<tag>content</tag> content
when it should just be
<tag>content</tag>
Can anyone see what I'm doing wrong here to cause this? Thank you! Jezzica85

Replies are listed 'Best First'.
Re: XML::Twig and paste
by mirod (Canon) on Jul 25, 2007 at 16:27 UTC

    The problem is in the loop: the first element is the root. The you get the next element, the tag element, which you print. Its content is <tag>content</tag>, then you take the next element: this one is the text (#PCDATA') element in the tag element, and you print it. Its content is content. Then you take the next element, there is none and you exit.

    So paste works, its just your understanding of next_element and print that was off.

      Thanks mirod, I'm still not sure I understand what you mean. Do you mean I have to skip every other element for this to work right? I thought in order to print out an entire document tree you had to print out from the root, regardless of how many elements there are in the tree. I only put one element in the tree for my example; in my real program there are more. Thanks, Jezzica85

        To print the document: $t->print prints the entire document. You don't have to do the inner loop yourself.