Re: How to import nodes to a new empty document ?

Imene Bensalem <[email protected]> Thu, 15 Nov 2012 16:57:03 +0100
Newsgroups gmane.comp.lang.perl.xml
Message-ID <CAJreDwG-OkqNM1NEw+rCahTmvmYBSCQMO7c8it7ORVxCB3qOuQ@mail.gmail.com>
Hi Shlomi,

Thank your response and your device.

This the entire code :
#####begin
use strict;
use warnings;
use XML::LibXML;

sub title_filter
{

    my $filename= $_[0];
    my $newfilename = "target.xml";
    my $parser = XML::LibXML->new();
    my $source_xml = $parser->parse_file($filename);
    my $target_xml = XML::LibXML->createDocument( "1.0", "UTF-8" );
    open my $out_fh, '>', $newfilename;
    #my $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;

}

title_filter('source.xml');

#### end

This is the content of source.xml

<?xml version="1.0" encoding="UTF-8"?> <book> <page> <title>title1</title>
<text>text1</text> </page> <page> <title>title2</title> <text>text2</text>
</page> </book>

What I want to do is to copy a page form source.xml and put it into
target.xml
I have to copy them page per page because I need to filter a page if its
title belong to a list ( PS. I did not yet add the portion of code that do
the task of filtering and I would appreciate to get a clue )
When I execute the code I received the following msg:
"Can't call method "appendChild" on an undefined value ..."
I understood that the problem is the absence of a root element in the new
docurment: target.xml
So I add the following instructions (I commented them in the above code):
my $root = $source_xml->documentElement();
$target_xml->setDocumentElement($root);

Therefor the result is: there is no error and target.xml contains the same
content as source.xml

but it seems that these two instructions copy the root element with all its
child to target.xml , and the remainder of the code   have no effect (i.e.
I obtain the same result if I delete the instruction:  for (@page) {....} )

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