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

All,

I have a need to create a new document and would like to do so with Twig. This right here works:

my $root = XML::Twig::Elt->new('project'); my $homePageProjectName = XML::Twig::Elt->new( projectName => $project +NameValue); $homePageProjectName->paste($root); print qq|<?xml version="1.0"?>|; $root->print;

and outputs this:

<?xml version="1.0"?><project><projectName>Test Project</projectName></project>

Which works fine, I suppose, but I really want it to do this full on twig style, losing that quoted print statement above. What I'm trying accomplish here is to read from one xml file and then output two new files. I can do the parsing fine now (thanks monks) and can extract specific elements from the tree. The challange for me is creating the two new files.

Thanks,
Eric

Replies are listed 'Best First'.
Re: Twig Question: Create a new XML doc using twig?
by mirod (Canon) on Mar 23, 2009 at 08:41 UTC

    You are creating, and printing, an element. If you want the XML declaration to be output, you can only do this on a complete twig. And of course you need to set the declaration for that twig, as it is optional.

    So replace your last 2 statements by the following code:

    my $twig= XML::Twig->new(); $twig->set_xml_version( '1.0'); $twig->set_root( $root); $twig->print;

    You can, of course, add option to new, like pretty_print => 'indented' for example.

Re: Twig Question: Create a new XML doc using twig?
by ramrod (Priest) on Mar 23, 2009 at 01:45 UTC
    Unless I'm missing the point, all you need to do is add the filehandle reference to your print statement.
    $root->print($file_handle);
    To print to two files, do this with two filehandles.

    Update:Removed quotes per GrandFather's comments. My apologies on the typo.
      $root->print('$file_handle');

      is unlikely to help - single quoted strings don't interpolate and in fact you probably don't mean to use a string there at all. Most likely you intended:

      $root->print($file_handle);

      True laziness is hard work