Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Twig Question: Create a new XML doc using twig?

by zericm (Novice)
on Mar 22, 2009 at 23:24 UTC ( [id://752452]=perlquestion: print w/replies, xml ) Need Help??

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 (Curate) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://752452]
Approved by igelkott
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-20 00:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found