XML :: LibXML:doc - root

时间:2013-07-21 15:43:32

标签: xml perl xml-parsing xml-libxml

这是第一个例子中documentElemtent的调用是多余的吗?

#!/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( '/' );

输出

#document

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

输出

#document

1 个答案:

答案 0 :(得分:2)

主题节点中定义的任何前缀都由xpc采用,因此如果在根节点上定义了前缀,则两者是不同的。

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