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

1. I have added child element using the below code and i need to add again child or descendants to the root tag. how can i do this?
2. First step i am changing the "indd_document" element to "docuemnt". i have a doubt here the xml::twig now recognize "docuemnt" or "indd_docuemnt" for my second twig_roots for update_header. Please suggest

use strict; use warnings; use XML::Parser; use XML::Twig; my $twig=XML::Twig->new( twig_roots=>{ i +ndd_document=>\&update_root, 'document/header'=>\&update_header +, }, ); $twig->parsefile( $xmlfile); open(FH,">output.xml") or die "cannot open output.xml: $!"; my $temp = $twig->toString; print FH $temp; close (FH); $twig->purge; } sub update_root { my ($t, $root) = @_; $root->insert_new_elt(first_child => header => {type=>"layout"}); $root->set_tag( 'document'); } sub update_header { my ($t, $header)=@_; $header->insert_new_elt(first_child => headerfield => {type=>"layout"} +); }
INPUT:
<?xml version="1.0"?> <indd_document> <para> </para> </indd_document>
OUTPUT:
<?xml version="1.0"?> <indd_document> <header> <headerchild name=""/> <headerchild name=""/> </header> <para> </para> </indd_document>

Replies are listed 'Best First'.
Re: xml::child add child and descendants
by mickep76 (Beadle) on Oct 08, 2009 at 13:46 UTC

    You can insert new children in any part of the Tree but not using handlers. Since the new child you already inserted will not be parsed.

    A good technique is to create a new node with the XML you want to insert.

    my $xml = <<__XML__; <whatever> ... </whatever> __XML__ my $twig2 = XML::Twig->new(); $twig2->parse($xml); my $elt2 = $twig2->root; $elt->insert_new_elt('first_child', 'foobar', $elt2);
Re: xml::child add child and descendants
by mirod (Canon) on Oct 08, 2009 at 13:14 UTC

    XML::Twig works on the original document, so no, it won't trigger on 'document'. I am not sure I understand very well why you would need to do this, could you explain a little more?

      Hi mirod,
      I have changed the 'indd_document' to 'document' element. in the twig_handler.
      After that if i want to check from //indd_docuemnt or if i want to check some xpath conditions. So i have a doubt here.

        You still check on the original indd_document, or forget about the root and just trigger on the element header, you don't have to put the whole hierarchy there.