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" }); }

In reply to Re: XHTML with XML::Twig - tree manipulation problem by mirod
in thread XHTML with XML::Twig - tree manipulation problem by nick

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.