How to import nodes to a new empty document ?

Imene Bensalem <[email protected]> Thu, 15 Nov 2012 09:42:51 +0100
Newsgroups gmane.comp.lang.perl.xml
Message-ID <CAJreDwHwCCv-iMjax=6YRBG1J0dUnE2CaZ57J3LW1wb+Ub82Vw@mail.gmail.com>
Hi all ,

I'm new in using XML with perl,
I want to create a new XML document and put inside it portions from another
one using  XML::LibXML (something like copy and past);

Example:

The source document

<book>
 <page>
   <title>xxxxxx</title>
   <text>xxxxxxx</text>
 </page>
 <page>
   <title>xxxxxxx</title>
   <text>xxxxxxxxx</text>
 </page>
</book>

the target created document should have the same structure but does not
contain all the pages (pages whose title belong to a "filter list" will not
be copied to the new document

This is the code I used but it does not work (it does not yet contain
instructions for the filter ):

use XML::LibXML;
my $filename= $_[0];
my $newfilename = "file-filtered.xml";
my $parser = XML::LibXML->new();
my $source_xml = $parser->parse_file($filename);
my $target_xml = XML::LibXML->createDocument( "1.0", "UTF-8" );
open $out_fh, '>', $newfilename;
#$root = $source_xml->documentElement();
#$target_xml->setDocumentElement($root);
my @pages = $source_xml->getElementsByTagName('page');
for (@pages)
{
     my $imported = $target_xml->importNode( $_ );
     $target_xml->documentElement->appendChild( $imported );
}
    print {$out_fh} $target_xml->toString;
    close $out_fh;

I receive the following message when I execute the code : "Can't call
method "appendChild" on an undefined value "
for this, I created a root in the new document using the 2 instructions in
comment, but those instructions copy in the new document the root with its
all content (=all the document),

I will appreciate very much your help.

_______________________________________________
Perl-XML mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs