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

I've been working on an XHTML parser, and for the most part I really like XML::Twig, it's very powerfull yet still fairly easy to use. However, there is still some weirdness that I cannot figure out how to fix.

For example, if I load in a valid XHTML document, add a field to it (such as a form tag), then output the parsed data. I would expect the output would be valid XHTML as well, but it isn't. See example:

This is my valid XHTML document:
<html> <head> <title>example</title> </head> <body> <text>Foo Bar</text> </body> </html>

Here is my code, which will insert a form tag into the body.
#!/usr/bin/perl -w use strict; use XML::Twig; sub main() { my $filename = $ARGV[0] ? $ARGV[0] : die "specify input filena +me.\n"; my @tags = ('input', 'textarea', 'checkbox'); my $xml = XML::Twig->new( keep_spaces_in => [ 'pre' ], pretty_print => 'indented', twig_roots => { 'body' => \&insert_form_tags, }, twig_print_outside_roots => 1, ); $xml->parsefile("$filename"); $xml->print; } sub insert_form_tags() { my ($xml, $body) = @_; my $form_group = 'process_group'; my $form_name = 'process_requirements'; my $form = $body->insert( form => { method => "Post", action => "submit.cgi", }, ); } &main();

This is simple code to input form tags, and it works, the form tags are inserted, however the output of XML::Twig generates invalid XHTML. See output:
<html> <head> <title>example</title> </head> </html> <html> <body> <form action="submit.cgi" method="Post"> <text>Foo Bar</text> </form> </body> </html>

Notice the closing, and then re-opening of the html tag right after the head, and before the body. When I try to parse this outputed file with XML::Twig it gets an error right at that spot. Removing the offending lines resolves the problem.

So my question is, how do I get XML::Twig to output valid XHTML after adding this form tag?

Thanks in advance for any help!

- Nick