Frage

Is the here the call of documentElemtent in the first example superfluous?

#!/usr/bin/env perl
use warnings;
use strict;
use XML::LibXML;

my $file = 'xml_file';

my $doc = XML::LibXML->load_xml( location => $file );
my $root = $doc->documentElement();
my $xpc = XML::LibXML::XPathContext->new( $root );
# ...
say $_->nodeName for $xpc->findnodes( '/' );

outputs

#document

$doc = XML::LibXML->load_xml( location => $file );
$xpc = XML::LibXML::XPathContext->new( $doc );
# ...
say $_->nodeName for $xpc->findnodes( '/' );

outputs also

#document
War es hilfreich?

Lösung

Any prefixes defined in the topic node are adopted by the xpc, so the two are different if there are prefixes defined on the root node.

use warnings;
use strict;
use feature qw( say );

use XML::LibXML qw( );

my $xml = <<'__EOI__';
<root xmlns:foo="uri:xxx">
<foo:bar/>
</root>
__EOI__

my $doc  = XML::LibXML->load_xml( string => $xml );
my $root = $doc->documentElement();

{
   my $xpc = XML::LibXML::XPathContext->new($doc);
   say "doc:";
   say $_->nodeName for $xpc->findnodes('foo:bar');
}

say "";

{
   my $xpc  = XML::LibXML::XPathContext->new($root);
   say "root:";
   say $_->nodeName for $xpc->findnodes('foo:bar');
}

doc:

root:
foo:bar
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top