http://qs1969.pair.com?node_id=229074


in reply to Another simple XML Twig question

You don't provide the input and expected outputs of your code fragment, so it is a little difficult to figure out what you want to do. Plus the code is obviously incorrect as you try to paste the same element ($ds_tag) twice.

Anyway, here is my take on it: I think you want to paste the newly created elements as children of the initial ds element, so you should use first_child or last_child instead of after when you paste them. Generally speaking you should not thing in terms of tags but in terms of elements. I think that's why you are confused and use after. In XML::Twig you process elements, which have one parent, possibly children and siblings. You process them in a tree, and then you can output this tree. You (normally) do not have to care about opening/closing tags, just put the element in the proper place and that will be taken care of by the module.

So here is an attempt at fixing your code. It is probably not what you want but it should help you getting there ;--):

#!/usr/bin/perl -w use strict; use XML::Twig; my $twig=XML::Twig->new( pretty_print => 'indented') ->parse( \*DATA); my @ds= $twig->root->children( 'ds'); foreach my $attr (@ds) { my $ds_elt= XML::Twig::Elt->new( 'ds'); # new XML::Twig::Elt is +deprecated # to create the element as a child use 'last_child', not 'after' # you might want to use 'first_child' instead, I don't know your d +ata $ds_elt->paste( last_child => $attr); # I like using => here my $unknown= "0"; my $unknown_elt= XML::Twig::Elt->new( unknown_sec => $unknown); # you initially tried to paste $ds_elt again # I don't know where you want to paste the element but I guess it' +s here # you might also want to have a look at the insert method that cre +ates # an element as the only child of the calling element, see # http://www.xmltwig.com/xmltwig/twig_dev.html#METHODS_XML_Twig_El +t_insert $unknown_elt->paste( first_child => $ds_elt); my $comment= " PDP Status "; # this is how you create a comment: with an element name '#COMMENT +' my $comment_elt= XML::Twig::Elt->new( '#COMMENT' => $comment); # you could also write $comment_elt->paste( last_child => $ds_elt +); $comment_elt->paste( 'after', $unknown_elt); my $min= "NaN"; my $min_elt= XML::Twig::Elt->new( min => $min); $min_elt->paste( after => $comment_elt); } $twig->print; __DATA__ <doc> <ds><content/></ds> <ds><content/></ds> </doc>

Replies are listed 'Best First'.
Re: Re: Another simple XML Twig question
by Anonymous Monk on Jan 22, 2003 at 17:37 UTC
    Thank you both for the help.
    Your comments are greatly appreciated, and I now know what I've done wrong.

    Thanks again!