in reply to XHTML with XML::Twig - tree manipulation problem
You need to get the form element, which is easy, it is returned by the insert method. Then you can insert a new element as first child of this element. You can use XML::Twig::Elt->new and then paste that element, or simply call $form->insert_new_elt, the arguments are the position (first_child), then the same arguments as for new: the element tag then a hasref of attributes. The code is below.
2 quick comments: if you are dealing with XHTML you want to use keep_spaces_in => to avoid XML::Twig messing up the whitespaces in pre tags, and you will not get exactly the output format you want, the input tag will be on the same line as the form one. If What is Foo? was in a p element (or any other element for what matters), then you would get the formating you want (and I suspect a better chance to get valid XHTML).
#!/usr/bin/perl -w use strict; use XML::Twig; my $xml = XML::Twig->new( keep_spaces_in => [ 'pre' ], # safer, other tags migh +t need to be included pretty_print => 'indented', twig_roots => { 'body' => \&insert_form_tags, }, ); $xml->parsefile('index.html'); $xml->print; sub insert_form_tags() { my ($t, $body) = @_; my $form= $body->insert( form => { method => "Post", action => "submit.cgi" }, ); $form->insert_new_elt( first_child => input => { type => "text", n +ame => "foo_is" }); }
|
|---|