Re: How to import nodes to a new empty document ?
Shlomi Fish <[email protected]> Thu, 15 Nov 2012 10:57:36 +0200
| Newsgroups | gmane.comp.lang.perl.xml |
|---|---|
| Message-ID | <[email protected]> |
Hi Imene, On Thu, 15 Nov 2012 09:42:51 +0100 Imene Bensalem <[email protected]> wrote: > 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; > First of all, it's good that you are using XML::LibXML, instead of, say, XML::Simple. Since $_[0] is not valid outside of subroutines, and your code also lacks "use strict;" and "use warnings;" it seems like you have provided non-self-contained code. See: http://shadow.cat/blog/matt-s-trout/show-us-the-whole-code/ You may also wish to peruse: http://perl-begin.org/tutorials/bad-elements/ Otherwise, it will be harder for us to help you. Regards, Shlomi Fish > 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. -- ----------------------------------------------------------------- Shlomi Fish http://www.shlomifish.org/ Stop Using MSIE - http://www.shlomifish.org/no-ie/ Real programmers don’t write workarounds. They tell their users to upgrade their software. Please reply to list if it's a mailing list post - http://shlom.in/reply . _______________________________________________ Perl-XML mailing list [email protected] To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs